Cleanest Way to Invoke Cross-Thread Events

Posted by Nick on Stack Overflow See other posts from Stack Overflow or by Nick
Published on 2008-08-22T13:34:02Z Indexed on 2012/10/05 9:37 UTC
Read the original article Hit count: 192

Filed under:
|
|

I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is.

Based on the community suggestions, I've used this:

// earlier in the code
mCoolObject.CoolEvent+= 
           new CoolObjectEventHandler(mCoolObject_CoolEvent);
// then
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
    if (InvokeRequired)
    {
        CoolObjectEventHandler cb =
            new CoolObjectEventHandler(
                mCoolObject_CoolEvent);
        Invoke(cb, new object[] { sender, args });
        return;
    }
    // do the dirty work of my method here
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading