c# - 多线程和委托(delegate)调用

标签 c# multithreading

假设我有一个在多个线程和委托(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);
}

我知道用作事件的方法必须同步才能线程安全等,但是如果

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

同时被调用?这可以吗?或者我是否需要同步分析:

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

所以问题更像是:从调用类的角度来看,像这样的“事件”线程安全吗(我知道我必须保证插入方法的线程安全)

最佳答案

引发事件的类可以在多个线程上同时执行此操作(如果这是您想要的行为)。 “事件”就像按顺序调用的方法列表。

每个单独的线程都会引发一个单独的事件,正如您所说,事件处理程序有责任处理由单独的事件在多个线程上调用的可能性(如果事件是这样设计的)。

从引发事件的类的角度来看,线程安全并不能很好地描述您所要求的内容,因为您正在混合术语。线程安全是关于在多线程情况下是否可以调用一个类来安全地完成其工作,这些线程不会通过类状态进行交互。

关于c# - 多线程和委托(delegate)调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39581831/

相关文章:

c# - 如果我的 C# AnyCPU 应用程序以 32 位 (WOW64) 运行,我如何以 64 位重新运行它?

java - 在带有实例变量的 block 上使用 synchronized

xcode - 编译时没有OpenSSL支持错误

asp.net - ASP.Net MVC 中长时间运行 SQL 查询的最佳实践

c# - .NET 检查两个 IEnumerable<T> 是否具有相同的元素

c# - 计时器不断加载场景而不是一次

c# - 无法使用 git 部署到 Azure

c# - 我如何知道我的异步方法已在 WCF 服务中完成?

c# - DispatcherOperations.Wait()

java - 在 Java 中重命名线程