简体   繁体   English

如何检查线程是否在C#中忙?

[英]How to check if a thread is busy in C#?

I have a Windows Forms UI running on a thread, Thread1 . 我有一个在线程Thread1上运行的Windows窗体UI。 I have another thread, Thread2 , that gets tons of data via external events that needs to update the Windows UI. 我有另一个线程Thread2 ,它通过需要更新Windows UI的外部事件获取大量数据。 (It actually updates multiple UI threads.) (它实际上更新了多个UI线程。)

I have a third thread, Thread3 , that I use as a buffer thread between Thread1 and Thread2 so that Thread2 can continue to update other threads (via the same method). 我有一个第三线程, Thread3 ,我作为之间的缓冲线程中使用Thread1Thread2 ,使得Thread2可以继续更新其他线程(通过相同的方法)。

My buffer thread, Thread3 , looks like this: 我的缓冲线程Thread3看起来像这样:

public class ThreadBuffer
{
    public ThreadBuffer(frmUI form, CustomArgs e)
    {
        form.Invoke((MethodInvoker)delegate { form.UpdateUI(e); });
    }
}

What I would like to do is for my ThreadBuffer to check whether my form is currently busy doing previous updates. 我想做的是让我的ThreadBuffer检查我的表单当前是否正在忙于执行以前的更新。 If it is, I'd like for it to wait until it frees up and then invoke the UpdateUI(e) . 如果是,我希望它等到它释放然后再调用UpdateUI(e)

I was thinking about either: 我在考虑:

a) 一个)

//PseudoCode

while(form==busy)
{
    // Do nothing;
}
form.Invoke((MethodInvoker)delegate { form.UpdateUI(e); });

How would I check the form==busy ? 我如何检查form==busy Also, I am not sure that this is a good approach. 另外,我不确定这是一个好方法。

b) Create an event in form1 that will notify the ThreadBuffer that it is ready to process. b)在form1中创建一个事件,它将通知ThreadBuffer它已准备好处理。

// psuedocode

List<CustomArgs> elist = new List<CustomArgs>();

public ThreadBuffer(frmUI form, CustomArgs e)
{
    from.OnFreedUp += from_OnFreedUp();
    elist.Add(e);
}

private form_OnFreedUp()
{
    if (elist.count == 0)
        return;
    form.Invoke((MethodInvoker)delegate { form.UpdateUI(elist[0]); });
    elist.Remove(elist[0]);
}

In this case, how would I write an event that will notify that the form is free? 在这种情况下,我将如何编写一个通知表单是免费的事件?

and

c) an other ideas? c)其他想法?

How would I check the form==busy ? 我如何检查表格==忙? Also, I am not sure that this is a good approach 另外,我不确定这是一个好方法

Control.Invoke effectively does this already. Control.Invoke已经有效地完成了这项工作。 There is no reason to "wait until the thread is not busy", as the Invoke call will not return until the method processes, which won't happen until the thread is not busy. 没有理由“等到线程不忙”,因为Invoke调用在方法处理之前不会返回,这在线程不忙之前不会发生。

You can just call Invoke and not worry about whether the UI thread is busy. 您可以只调用Invoke而不用担心UI线程是否繁忙。

您可能会看到一个事件

System.Windows.Forms.Application.Idle 

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

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