简化后台工作者的匿名方法

时间:2015-03-08 01:22:39

标签: c# delegates backgroundworker anonymous-function

我正在尝试通过按钮点击创建所有代码,在后台工作程序中运行。所以我有以下代码模板。

BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += delegate
{
    //code
};
backgroundWorker.RunWorkerAsync();
while (backgroundWorker.IsBusy)
{
    Application.DoEvents();
} 

只是想知道是否有办法简化这段代码,所以我没有有效地为所有按钮复制相同的代码块。

编辑: 我试图运行的典型代码是:

//Synchronous task
Wait(2000);
//Synchronous task
return taskResult ? "Success" : "Failure"

1 个答案:

答案 0 :(得分:7)

如果没有更多的背景,就不可能提出非常具体的改进。也就是说,肯定你可以摆脱while循环。只需使用:

BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += delegate
{
    //code
};
backgroundWorker.RunWorkerAsync();

请注意,如果您希望在BackgroundWorker任务完成时执行代码(可能解释为什么您首先拥有while循环),那么这样的代码将起作用(而不是使用之前的while循环):

BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += delegate
{
    //code
};
backgroundWorker.RunWorkerCompleted += (sender, e) =>
{
    // code to execute when background task is done
};
backgroundWorker.RunWorkerAsync();

在现代C#中,BackgroundWorker几乎已经过时了。它现在提供的主要好处是方便的进度报告,实际上很容易通过使用Progress<T>来获得。

如果您不需要报告进度,请将代码分解为使用async / await很简单:

await Task.Run(() =>
{
    //code
});

// code to execute when background task is done

如果您确实需要报告进度,那只会稍微困难一些:

Progress<int> progress = new Progress<int>();

progress.ProgressChanged += (sender, progressValue) =>
{
    // do something with "progressValue" here
};

await Task.Run(() =>
{
    //code

    // When reporting progress ("progressValue" is some hypothetical
    // variable containing the progress value to report...Progress<T>
    // is generic so you can customize to do whatever you want)
    progress.Report(progressValue);
});

// code to execute when background task is done

最后,在某些情况下,您可能需要该任务返回一个值。在那种情况下,它看起来更像是这样:

var result = await Task.Run(() =>
{
    //code

    // "someValue" would be a variable or expression having the value you
    // want to return. It can be of any type.
    return someValue;
});

// At this point in execution "result" now has the value returned by the
// background task. Note that in the above example, the method itself
// is anonymous and so you could just set a local variable at the end of the
// task; the value-returning syntax is more useful when you are calling an
// actual method that itself returns a value, and is especially useful when
// you are calling an `async` method that returns a value (i.e. you're not
// even using `Task.Run()` in the `await` statement.

// code to execute when background task is done

您可以根据需要混合使用上述技术。