我试图通过单击按钮使我的所有代码都在后台工作程序中运行。所以我有以下代码模板。

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"

最佳答案

没有更多的背景信息,就不可能提出非常具体的改进建议。也就是说,可以肯定地摆脱了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


您可以根据需要混合和匹配上述技术。

关于c# - 简化后台工作人员的匿名方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28922074/

10-13 03:11