views:

173

answers:

2

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();
        }
    }
}
+1  A: 

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.

Matt Davis
Ta. I guess my main concern was that I wan't entirely sure whether the object actually existed until the constructor had finished or not.
Nicholas
I know someone else can explain it better than me, but it doesn't have anything to do with whether A exists or not. You've registered an object of type System.Delegate with the event. The delegate exists, and that's what matters. Still, based on your comment, I double-checked with a quick example in Visual Studio, and it works as I described it.
Matt Davis
+1  A: 

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.

jasonh
Anyone care to explain why my answer was downvoted?
jasonh