Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Windows Forms UI running on a thread, Thread1. I have another thread, Thread2, that gets tons of data via external events that needs to update the Windows UI. (It actually updates multiple UI threads.)

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).

My buffer thread, Thread3, 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 for my ThreadBuffer to check whether my form is currently busy doing previous updates. If it is, I'd like for it to wait until it frees up and then invoke the 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? 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.

// 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?

like image 407
Sam Avatar asked Jan 27 '12 22:01

Sam


1 Answers

There is an event that you might look at

System.Windows.Forms.Application.Idle 
like image 168
MaLio Avatar answered Oct 25 '22 01:10

MaLio