简体   繁体   English

多线程和委托调用

[英]Multithread and delegate calls

Supose I have a method that runs in several threads and a delegate.假设我有一个在多个线程和一个委托中运行的方法。

public delegate void Del(string threadId, string value, ref string result);

public event Del Analyze= null;  // The external world can plug in a method


// this method runs simultanioulsy in several threads
private void threaded()
{
   string s= null;
   // yadayada s gets a value and I want a result back
   // from the external world
   string result = null;

   is (Analyze != null)
      Analyze("some thread id", s, ref result);
}

I am aware that the method used as an event must synchronize in order to be thread safe, etc, but what happens if我知道用作事件的方法必须同步才能保证线程安全等,但是如果

Analyze("some thread id", s, ref result);

gets called at the same time?同时被调用? Is that OK?这可以吗? Or do I need to synchronize Analyze like:或者我需要像分析一样同步:

lock(someobj)
{
    Analyze("some thread id", s, ref result);
}

So the question is more like: is an "event" like this thread safe from the point of view of the calling class (I know I must guarantee the thread safety of plugged in method)所以问题更像是:从调用类的角度来看,像这个线程这样的“事件”是否安全(我知道我必须保证插入方法的线程安全)

The class that raises the event can do so simultaneously on multiple threads if that is the behaviour you want.如果这是您想要的行为,引发事件的类可以在多个线程上同时进行。 An "event" is like a list of methods that get called in order. “事件”就像是按顺序调用的方法列表。

Each separate thread will be raising a separate event and as you say it is the event handlers duty to deal with the possibility of being called on multiple threads by separate events if that is how that event is designed.每个单独的线程将引发一个单独的事件,正如您所说,如果事件是这样设计的,则事件处理程序有责任处理被单独事件在多个线程上调用的可能性。

Thread safety from the point of view of the class raising the event is not a good description of what you are asking because you are mixing terms.从引发事件的类的角度来看,线程安全并不能很好地描述您所要求的内容,因为您混淆了术语。 Thread safety is about whether a class can be called to do its work safely in a multithreaded situation, that those threads don't interact via the classes state.线程安全是关于在多线程情况下是否可以调用一个类来安全地完成它的工作,这些线程不通过类状态进行交互。

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

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