简体   繁体   English

使用C#在运行时创建事件处理程序

[英]Creating eventhandler at runtime in c#

I'm creating an array of BackgroundWorker that shares one event handler like this: 我正在创建一个BackgroundWorker数组,该数组共享一个事件处理程序,如下所示:

BackgroundWorker[] workers = new BackgroundWorker[files.length];

for(int i = o; i<files.length; i++)
{
      workers[i] = new BackgroundWorker();
      workers[i].DoWork += new DoWorkEventHandler(worker_DoWork);
      workers[i].RunWorkerCompleted += newRunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
      workers[i].RunWorkerAsync(files[i]);
}

All workers are sharing the same event handler which does same thing only with different argument and result like this: 所有工作人员共享同一个事件处理程序,该事件处理程序仅使用不同的参数和结果来执行相同的操作,如下所示:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
         e.Result = ComputeSomething(e.Argument.ToString());
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
            resultArray.Add(e.Result);
}

private int ComputeSomething(string file)
{
         ...
         return number;
}

obviously in the code, I'm trying to make a list of BackgroundWorker that runs asyncronously but when I checked the results, some of them are incorrect. 显然,在代码中,我试图列出异步运行的BackgroundWorker,但是当我检查结果时,其中一些是不正确的。 I'm guessing that the value of "e.result" were replaced by other workers since they share the same event handler if that is the case then i would like to create Individual event handlers for each BackgroundWorker so that the value of e.result won't get replaced. 我猜想“ e.result”的值已被其他工作程序替代,因为如果这样的话,它们共享同一个事件处理程序,那么我想为每个BackgroundWorker创建个人事件处理程序,以便e.result的值不会被替换。 How will i do that? 我该怎么做?

Try synchronizing the access to resultArray: 尝试同步对resultArray的访问:


private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    lock(resultArray)
        resultArray.Add(e.Result);
}

Sharing the same event handler method shouldn't be a problem - it's the BackgroundWorker which provides the "e" in which you store the result. 共享相同的事件处理程序方法应该不是问题-它是BackgroundWorker提供用于存储结果的“ e”。

On the other hand, you are accessing resultArray from multiple threads. 另一方面,您正在从多个线程访问resultArray That could be causing a problem. 那可能会引起问题。 What sort of errors are you seeing in the results? 您在结果中看到什么样的错误? Other than the way you're combining the results at the end, I'd expect it to be okay. 除了您最终合并结果的方式之外,我希望它还可以。

I don't see how e.Result could be replaced by other workers. 我不知道e.Result可以如何被其他工作人员取代。 When you say some results are incorrect, do you mean the value is wrong, that there's no value at all, or maybe some results are duplicated while others disappear? 当您说某些结果不正确时,是否表示值是错误的,根本就没有任何价值,或者某些结果是重复的而其他结果却消失了? It seems to me you should put a synclock when adding to resultsArray to make sure it's thread-safe. 在我看来,添加到resultsArray时应该放置一个同步锁,以确保它是线程安全的。

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

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