我会为此使用Task Parralell Library。一个很好的教程是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
可能从后台线程抛出的任何异常。
我希望这有帮助。