Wiring threaded C# events in constructor
If a non-gui object constructor wires a local event handling method to the event field of an object on a different thread, is it possible for said event handling method to be called before the constructor is finished?
Example: (semantic pseudocode only)
public static B b = new B();
class A
{
public A()
{
b.开发者_如何转开发evt += EventHandler();
Thread.Sleep(5000);
}
protected void EventHandler()
{
// Some stuff
}
}
class B
{
public event evt;
public void ThreadedLoop()
{
while (true)
{
RaiseEvt();
}
}
}
Yes, because the event handling method is called in the context of the other thread.
In your example, the event handler is a method of class A, but when it is invoked, it is invoked in the context of the thread represented by class B. When the thread executing class A's constructor sleeps, the thread represented by class B will go to work, raising the event and calling the event handler in the process.
One thing to keep in mind is that the entire object isn't on another thread. If that object has a routine executing in a different thread, then any calls that object makes directly will be executed on the same thread. This includes delegate invocations.
So, your object doesn't exist on a particular thread, but the routines executing from it do. And when someone calls one of your routines from another thread, that routine will be executed on the other thread. This is important, because the class level data you have doesn't belong to one thread in particular. If you don't handle the fact that the invocation is happening from another thread, you can end up with concurrency issues and corruption of your object's class level data.
精彩评论