简体   繁体   English

带有事件处理程序和多线程的 C# 类

[英]C# class with event handlers and multiple threads

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.我知道每次调用 OnEvent 时,它都会在调用线程上下文中运行,这对我来说没问题。 My 2 questions are:我的两个问题是:

  1. Do I need to protect the OnEvent handler?我需要保护 OnEvent 处理程序吗? Like喜欢

    lock (someObject) { if (OnEvent != null) OnEvent(someString, out response);锁 (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).如果多个线程同时调用 OnHandler 并且处理程序只有线程安全代码(例如只有局部变量用于处理),会发生什么情况。 Is it OK to use the handler without protection then?那么可以在没有保护的情况下使用处理程序吗?

Do I need to protect the OnEvent handler?我需要保护 OnEvent 处理程序吗?

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;

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.对于数字 1,如果事件处理程序是线程安全的,则否,如果不是,则是,但最好将其锁定在处理程序中,而不是您调用它的地方。 For number 2, as long as the variables are local it is thread safe.对于数字 2,只要变量是本地的,它就是线程安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM