Domanda

I am wondering if this approach has potential to deadlock.

Sample code: When you click an app button, a Job object is created and Added to a job list. The Add code is 'lock' protected. Then on a timer tick event, I want to remove completed jobs from the list -- locking the list in the timer event.

So the question is, if the user presses the Add Job button, while the timer event has the lock in use, will this app deadlock?

Timer is a Windows Forms Timer.

public partial class Form1 : Form
{
    object listLock = new object();
    List<Job> jobsList = new List<Job>();
    public Form1()
    {
        InitializeComponent();
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        Job aJob;
        lock(listLock)
        {
            for (int i = jobsList.Count - 1; i > -1; i--)
            {
                aJob = jobsList[i];
                if (aJob.IsCompleted)
                {
                    jobsList.RemoveAt(i);
                }

            }
        }

    }

    private void button1_Click(object sender, EventArgs e)
    {
        lock (listLock)
        {
            Job aJob = new Job();
            jobsList.Add(aJob);
        }

    }
}

//=====================================
  class Job
    {
        bool isCompleted = false;

        public bool IsCompleted
        {
            get { return isCompleted; }
            set { isCompleted = value; }
        }

        public Job()
        {
            // do some work then mark complete
            IsCompleted = true;
        }
}
È stato utile?

Soluzione

Timer events (from Windows Forms Timer) are dispatched from the main message loop. So they will never overlap with the handler for any other UI event.

The button press will go into the message queue, and be processed after the timer Tick handler completes. (As a result, you don't need a lock for data structures which are only manipulated by UI event handlers, since they will run sequentially, in the order they were queued)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top