Events and multithreading

  • Thread starter Thread starter Zürcher See
  • Start date Start date
Z

Zürcher See

The event is thread safe? If a class call a delegate for an event, is the
class thread to execute the code or is the thread that has itself registered
that execute the code?
In few words if a form contains an object with a working thread, and the
working thread want to update something on the form, is threadsafe the call
to the event?

//the form register itself for the UpdateSomethingOnTheForm event and than
call the StartTheWorkingThread() method

class MyClass
{
public event EventHandler UpdateSomethingOnTheForm;

public void StartTheWorkingThread()
{
ThreadPoll.QueueUserWorkingItem(new
WaitCallBack(this.TheWorkingThreadMethod));
}

public void TheWorkingThreadMethod(object state)
{
....working...

//Now I want to update something on the form, this is thread safe?
this.UpdateSomethingOnTheForm(this,new EventHalder());

...working...
}

}
 
Zürcher,

Events are not thread safe. If an event is fired on another thread,
then the event handler is executed on that thread.

This is especially important when making calls to event handlers that
update the UI. You have to pass your delegate (and any parameters to the
method) through the Invoke method for the control on the form that you want
to update. This will allow the call to take place on the thread that
created the UI.

Hope this helps.
 
Thank's

Nicholas Paldino said:
Zürcher,

Events are not thread safe. If an event is fired on another thread,
then the event handler is executed on that thread.

This is especially important when making calls to event handlers that
update the UI. You have to pass your delegate (and any parameters to the
method) through the Invoke method for the control on the form that you want
to update. This will allow the call to take place on the thread that
created the UI.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Zürcher See said:
The event is thread safe? If a class call a delegate for an event, is the
class thread to execute the code or is the thread that has itself
registered
that execute the code?
In few words if a form contains an object with a working thread, and the
working thread want to update something on the form, is threadsafe the
call
to the event?

//the form register itself for the UpdateSomethingOnTheForm event and than
call the StartTheWorkingThread() method

class MyClass
{
public event EventHandler UpdateSomethingOnTheForm;

public void StartTheWorkingThread()
{
ThreadPoll.QueueUserWorkingItem(new
WaitCallBack(this.TheWorkingThreadMethod));
}

public void TheWorkingThreadMethod(object state)
{
....working...

//Now I want to update something on the form, this is thread safe?
this.UpdateSomethingOnTheForm(this,new EventHalder());

...working...
}

}
 
Back
Top