January 14, 2006
@ 04:11 PM

private void exitMenuItem Click(object sender, EventArgs e)
{
    if (runtime != null && runtime.Running)
    {
        ThreadPool.QueueUserWorkItem(delegate(object obj)
        {

            runtime.Stop();
            Invoke(new ThreadStart(delegate()
            {

                this.Close();
            }));
        });
    }
    else
    {
        this.Close();
    }
           
}

Just caught myself coding this up. The shown method is a Windows Forms event handler for a menu item. The task at hand is to check a local variable and if that’s set to a specific value, to switch to a different thread and perform an action (that particular job can’t be done on the Windows Forms STA thread), and to close the form back on the main STA thread once that’s done. I colored the executing threads; yellow is the Windows Forms STA thread, blue is an arbitrary pool thread. Works brilliantly. Sick, eh?

 

[Mind that I am using ThreadStart just because it’s a convenient void target(void) delegate]

Sunday, January 15, 2006 1:11:02 AM UTC
It took me a couple of minutes to realize what it happening there.
I tend to do much the same to handle mutli threading, only not with anonymous delegates.

I really liked sending anonymous delegate to the Invoke, though.
Sunday, January 15, 2006 2:05:38 AM UTC
Bitchin.
Tuesday, January 17, 2006 2:28:35 PM UTC
I just read [on Stephen Forte's Blog] about you joining WCF team @ Microsoft. I am glad to hear that and wish you all the best.
cheers!
Saturday, January 21, 2006 1:24:11 PM UTC
You should use MethodInvoker instead of ThreadStart. IIRC MethodInvoker and EventHandler are special-cased in the Control.Invoke implementation and perform faster than other delegates. Nice trick overall :))
Anonymous Coward
Comments are closed.