2

pseudo-code:

class A
{
    Dictionary<string, object> dic = new Dictionary<string, object>();
    public Do()
    {
        some_a.SomeEvent += (s, e) =>
                 {
                     dic["some_string"] = new object();
                 };   
         dic["some_other_string"] = new object();
    }
}

Is this safe? It would be if both dictionary operations were on single same thread. So are they?

EDIT In my situation event is fired in the same thread as Do, so it's safe.

ren
  • 3,843
  • 9
  • 50
  • 95
  • well, it depends on what thread your "some_a" object invokes the SomeEvent Handler. if yes, assume it´s safe, otherwise, no. – Joachim Kerschbaumer Aug 17 '12 at 10:38
  • You can detect which thread you are running on by using something like Console.Write(System.Threading.Thread.CurrentThread.ManagedThreadId); – AlSki Aug 17 '12 at 10:41

3 Answers3

3

The code inside the event handler will execute on the thread the event is raised on.

class AsyncWorker
{
    public void BeginWork()
    {
        new TaskFactory().StartNew(() => RaiseMyEvent());
    }

    public event EventHandler MyEvent;

    private void RaiseMyEvent()
    {
        var myEvent = MyEvent;
        if(myEvent != null)
            myEvent(EventArgs.Empty);
    }
}

var worker = new AsyncWorker();
worker.MyEvent += (s, e) =>
                  {
                      /* I will be executed on the thread
                         started by the TaskFactory */
                  };
worker.BeginWork();
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
3

An event happens (usually) on the thread that invokes the event. So we can't actually comment completely since you don't show the code that causes the event to be invoked!

Strictly speaking, the event could be on any thread - either because a random thread is calling OnSomeEvent (or whatever the trigger is), or if the OnSomeEvent implementation chooses to use BeginInvoke for some reason, but this is unlikely.

Ultimately, it comes down to: is there a reason to think multiple threads are involved in this code.

But: what absolutely is not the case: no, there is nothing that will make that event automatically happen on the thread that subscribes it. An event subscription is just an object+method pair; no thread is nominated in the subscription.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

Unless you specifically start the event handler in a different thread, both operations will indeed run on the same thread (assuming a single threaded application).

Oded
  • 489,969
  • 99
  • 883
  • 1,009