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

I have a Windows Forms user interface running on a thread, Thread1 . I have another thread, Thread2 , which receives a lot of data through external events that need to be updated on the Windows interface. (It actually updates multiple user interface threads.)

I have a third Thread3 thread, which I use as a buffer thread between Thread1 and Thread2 , so that Thread2 can continue to update other threads (using the same method).

My Thread3 buffer stream looks like this:

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

What I would like to do is my ThreadBuffer to check if my form is really busy with previous updates. If so, I would like it to wait for it to free, then call UpdateUI(e) .

I thought about it:

a)

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

How can I check form==busy ? Also, I'm not sure if this is a good approach.

b) Create an event in form1 that notifies ThreadBuffer that it is ready to be processed.

 // 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) other ideas?

+4
source share
2 answers

How can I check the form == busy? Also, I'm not sure if this is a good approach.

Control.Invoke effectively does this already. There is no reason to β€œwait until the thread is busy,” since the Invoke call will not return until the process processes the process, which will not be executed until the thread is busy.

You can simply invoke Invoke and not worry if the UI thread is busy.

+2
source

There is an event that you can look at

 System.Windows.Forms.Application.Idle 
+2
source

Source: https://habr.com/ru/post/1393450/


All Articles