1

I have a class with some event handlers. The class creates several threads that can use those handlers (if they are assigned). In pseudo-code:

public class Test
{
    public SomeEventKind OnEvent;
    public Test()
    {
        for (int i = 0; i < 10; i++)
            new Thread(multiThreaded).Start();
    }

   /// several threads running this
   private void multiThreaded()
   {
       string response;
      //some code
      if (OnEvent != null)
         OnEvent(someString, out response);
   }
}

I understand that every time OnEvent is called it will be running in the calling thread context and that's OK with me. My 2 questions are:

  1. Do I need to protect the OnEvent handler? Like

    lock (someObject) { if (OnEvent != null) OnEvent(someString, out response); }

  2. What happens if the OnHandler is called by several threads at the same time and the handler only have thread safe code (like only local variables for processing). Is it OK to use the handler without protection then?

Ulf Honkanen
  • 119
  • 1
  • 8
  • Possible duplicate of [Raise event thread safely - best practice](https://stackoverflow.com/questions/3668953/raise-event-thread-safely-best-practice) – Alex Netkachov Feb 26 '18 at 17:35
  • These all come down to your requirements. Do you *want* to raise multiple events at the same time or not, and do your handlers properly handle events being raised at the same time. We can't answer either of those questions for you. – Servy Feb 26 '18 at 17:44
  • Does this answer your question? [Checking for null before event dispatching... thread safe?](https://stackoverflow.com/questions/282653/checking-for-null-before-event-dispatching-thread-safe) – Zer0 Feb 04 '21 at 23:23
  • [C# Events and Thread Safety](https://stackoverflow.com/questions/786383/c-sharp-events-and-thread-safety). You'll rarely see thread-safe components that expose events. Events are inherently unsuitable for multithreaded environments. – Theodor Zoulias Feb 04 '21 at 23:54

2 Answers2

0

Do I need to protect the OnEvent handler?

Yes, but that's easy enough:

OnEvent?.Invoke(someString, out response);

Or this:

var temp = OnEvent;
if (temp != null)
    temp(someString, out response)

Is it OK to use the handler without protection then?

No

//This could evaluate to true here
if (OnEvent != null)
    //And then throw null ref exception here
    OnEvent(someString, out response);

Side note, that's a delegate, not an event. This is an event:

public event SomeDelegateType OnEvent;
Zer0
  • 7,191
  • 1
  • 20
  • 34
-1

For number 1, If the event handler is thread safe then no, if it's not then yes but it's better to lock it in the handler not where you call it. For number 2, as long as the variables are local it is thread safe.

Donald
  • 1
  • 3