Execution context for an event handler

M

mehdi_mousavi

Hi folks,
Consider the following code:

MyClass c = new MyClass();
c.MyEvent += new MyEventHandler(MyHandler);

where MyClass is defined as follows:

public class MyClass
{
public delegate void MyEventHandler(object sender, EventArgs e);
public event MyEventHandler MyEvent = null;

//Other things go here...
}

and MyHandler is defined this way:

private void MyHandler(object sender, EventArgs e) {}

The question is that what context the "MyHandler" method is executed
on? Is it executed under the same thread where the Event Handler is
called? or does it use the "thread pool" to execute the handler on
another thread?

Any help would be highly appreciated,

Cheers,
Mehdi
 
J

Jon Shemitz

mehdi_mousavi said:
c.MyEvent += new MyEventHandler(MyHandler);
public class MyClass
{
public delegate void MyEventHandler(object sender, EventArgs e);
public event MyEventHandler MyEvent = null;

//Other things go here...
}
The question is that what context the "MyHandler" method is executed
on? Is it executed under the same thread where the Event Handler is
called? or does it use the "thread pool" to execute the handler on
another thread?

Assuming that MyClass raises the event in the normal way

protected void OnEventHandler(EventArgs e)
{
if (MyEventHandler != null)
MyEventHandler(this, e);
}

then the "MyHandler" method is executed in the thread that called
OnEventHandler.

An OnEventHandler method *can* use a thread pool thread to execute the
"MyEventHandler(this, e);" call, in which case the handlers would all
be run on the thread pool thread, but this is not as common as
invoking the delegate directly.
 
S

Stoitcho Goutsev \(100\)

Mehdi,

It depends how the class invokes the handler. If the class uses simple call
e.g. MyEvent(this, e); then all event handler will be executed by the thread
executing event invocation code. Hoever delegates supprot BeginInvoke method
that will execute the handlers in a thread from the thread pool. In addition
the class itself can create a thread to execute the event handlers.

The most common scenario is event handler to be executed synchronously i.e.
no additional threads involved.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top