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:
Do I need to protect the OnEvent handler? Like
lock (someObject) { if (OnEvent != null) OnEvent(someString, out response); }
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?