Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Events between threads executed in their own thread (How to)?

Tags:

I'd like to have two Threads. Let's call them :

  • Thread A
  • Thread B

Thread A fires an event and thread B listen to this event. When the Thread B Event Listener is executed, it's executed with the Thread A's thread ID, so i guess it is executed within the Thread A.

What I'd like to do is be able to fire event to Thread B saying something like: "hey, a data is ready for you, you can deal with it now". This event must be executed in its own Thread because it uses things that only him can access (like UI controls).

How can I do that ?

Thank you for you help.

like image 222
Guillaume Avatar asked Mar 08 '10 19:03

Guillaume


2 Answers

You'll need to marshal the information back into the UI thread.

Typically, you would handle this in your Event handler. For example, say Thread A was your UI thread - when it subscribed to an event on an object in Thread B, the event handler will be run inside Thread B. However, it can then just marshal this back into the UI thread:

// In Thread A (UI) class...
private void myThreadBObject_EventHandler(object sender, EventArgs e)
{
    this.button1.BeginInvoke( new Action(
        () => 
            {
                // Put your "work" here, and it will happen on the UI thread...
            }));
}
like image 107
Reed Copsey Avatar answered Sep 29 '22 14:09

Reed Copsey


The easiest way is probably to subscribe using an event handler which just marshal the "real" handler call onto thread B. For instance, the handler could call Control.BeginInvoke to do some work on thread B:

MethodInvoker realAction = UpdateTextBox;
foo.SomeEvent += (sender, args) => textBox.BeginInvoke(realAction);

...

private void UpdateTextBox()
{
    // Do your real work here
}
like image 20
Jon Skeet Avatar answered Sep 29 '22 16:09

Jon Skeet