1

我有一个使用 lambda 创建的后台工作程序,如下所示:

BackgroundWorker fileCountWorker= new BackgroundWorker();
fileCountWorker.WorkerSupportsCancellation = true;
fileCountWorker.DoWork += new DoWorkEventHandler((obj, e) => GetFileInfo(folder, subs));
fileCountWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((obj, e) => UpdateCountInFolderListViewForItem(index));
fileCountWorker.RunWorkerAsync(); 

我希望能够取消后台工作程序,然后知道它是在 RunWorkerCompleted 函数中使用 RunWorkerCompletedEventArgs e.Canceled 属性取消的。

到目前为止,我一直无法找到一种将参数传递给 RunWorkerCompleted 函数并仍然保持访问 RunWorkerCompletedEventArgs 的能力的方法。

我尝试将 RunWorkerCompletedEventArgs 参数添加到 RunWorkerCompleted 调用的函数中,然后像这样传递 RunWorkerCompletedEventArgs:

fileCountWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((obj, e) => UpdateCountInFolderListViewForItem(index, e));

但这似乎不起作用。

有没有办法做到这一点?

编辑

根据以下评论,我进行了以下更改:

我将 DoWork 事件更改如下(在工作函数中添加 obj 和 e 作为参数):

fileCountWorker.DoWork += new DoWorkEventHandler((obj, e) => GetFileInfo(folder, subs,obj,e));

然后我将 RunWorkerCompleted 函数更改如下(在 RunWorkerCompleted 函数中添加 obj 和 e 作为参数):

fileCountWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((obj, e) => UpdateCountInFolderListViewForItem(index, obj, e));

从我的 UI 线程中,我调用 CancelAsync:

if (bgw.WorkerSupportsCancellation)
   {
      bgw.CancelAsync();
   }

然后从后台工作人员中检查取消挂起,例如:

BackgroundWorker bwAsync = sender as BackgroundWorker;
if (bwAsync.CancellationPending)
   {
      e.Cancel = true;
      return;
   }

结果是,当我取消backgroundworker时,它确实停止了worker函数,但是RunWorkerCompleted函数(UpdateCountInFolderListViewForItem)中的RunWorkerCompletedEventArgs仍然有一个Canceled属性设置为False,所以函数无法判断worker被取消了。

所以我仍然坚持让 RunWorkerCompleted 函数知道工人被取消而不是正常完成。

4

1 回答 1

0

你只需要打电话BackgroundWorker.CancelAsync()

你的工作代码需要检查BackgroundWorker.CancellationPending并停止它正在做的“取消”......但是,你的 lambda 没有做任何你可以真正取消的事情。

通常你会做的是这样的:

//...
fileCountWorker.DoWork += (obj, e) =>
{
    for (int i = 0; i < 1000 && fileCountWorker.CancellationPending; ++i)
    {
        Thread.Sleep(500);/* really do other work here */
    }
    e.Cancel = fileCountWorker.CancellationPending;
};

fileCountWorker.RunWorkerAsync(); 

//...

fileCountWorker.CancelAsync();

如果您提供 的一些详细信息GetFileInfo,也许可以提供更多详细信息。

于 2013-03-24T01:09:58.670 回答