all groups > dotnet windows forms > august 2006 >
You're in the

dotnet windows forms

group:

Execution context for an event handler



Execution context for an event handler mehdi_mousavi
8/30/2006 5:32:42 AM
dotnet windows forms: 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
Re: Execution context for an event handler Jon Shemitz
8/30/2006 11:02:07 AM
[quoted text, click to view]

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.

--

..NET 2.0 for Delphi Programmers www.midnightbeach.com/.net
Re: Execution context for an event handler Stoitcho Goutsev (100)
8/30/2006 4:37:35 PM
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.

--
HTH
Stoitcho Goutsev (100)

[quoted text, click to view]

AddThis Social Bookmark Button