简体   繁体   English

在Timer Tick事件中使用'lock'是死锁吗?

[英]Is it Deadlock Safe to use 'lock' in a Timer Tick event?

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. 示例代码:单击应用程序按钮时,将创建一个Job对象并将其添加到作业列表中。 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. Timer是一个Windows窗体计时器。

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;
        }
}

Timer events (from Windows Forms Timer) are dispatched from the main message loop. 定时器事件(来自Windows窗体定时器)从主消息循环调度。 So they will never overlap with the handler for any other UI event. 因此,它们永远不会与任何其他UI事件的处理程序重叠。

The button press will go into the message queue, and be processed after the timer Tick handler completes. 按下按钮将进入消息队列,并在计时器Tick处理程序完成后进行处理。 (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) (因此,您不需要锁定仅由UI事件处理程序操纵的数据结构,因为它们将按顺序运行,按排队顺序运行)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM