在一些代码中看到了这一点,但对我来说却毫无意义,所以我想知道这是否是利用backgreound工作者的正确方法?
它在Form_Load事件中像这样使用:
BackgroundWorker asyncWorker = new BackgroundWorker();
asyncWorker.DoWork += new DoWorkEventHandler(AsynchDoWork);
asyncWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(AsynchCompleted);
asyncWorker.RunWorkerAsync();
// a for each loop that can take some time to populate a combobx on the form
此外,在实现相同目标方面还有更好的选择吗?除了背景工作者?
最佳答案
我将为此使用Task Parralell库。一个很好的教程是Task Parallel Library: 1 of n。要根据某些后台任务的结果更新组合框,您可以执行以下操作
// Get UI scheduler. Use this to update ui thread in continuation.
TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
// You can use TPL like this...
List<object> objList = new List<object>();
Task<object[]> task = Task.Factory.StartNew<object[]>(() =>
{
// Pull all your data into some object.
object[] objArr = new object[] { "Some", "Stuff", "..." };
return objArr;
}, TaskCreationOptions.PreferFairness);
// Continuation firs after the antecedent task is completed.
task.ContinueWith(ant =>
{
// Get returned data set.
object[] resultSet = (task.Result as object[]);
// Check task status.
switch (task.Status)
{
// Handle any exceptions to prevent UnobservedTaskException.
case TaskStatus.RanToCompletion:
if (task.Result != null)
{
// Update UI comboBox.
}
break;
default:
break;
}
}, CancellationToken.None, TaskContinuationOptions.None, uiScheduler);
在这里,
uiScheduler
允许您从延续委托中更新ui线程,该延续线程将在先前任务完成(无论成功还是失败)时触发。在这种情况下,延续也充当异常处理程序,以捕获可能从后台线程抛出的任何
AggregateExceptions
。我希望这有帮助。
关于c# - 这是使用后台 worker 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12372764/