Wenn Sie .NET 4.0+ verwenden, dann können Sie die TPL . Der Code würde etwa so aussehen:
var task1 = Task.Factory.StartNew<int>(()=>
{
//Do Work...use closures, or you can pass boxed arguments in
//via StartNew params
return 1;//return the value that was computed
});
var task2 = Task.Factory.StartNew<int>(()=>
{
//Do Work
return 2;//return the value that was computed
});
task1.ContinueWith((previousTask)=>
{
//Return back to the main thread
label1.Text += "The value of task1 is going to be 1-->"
+ previousTask.Result;
}
, new CancellationTokenSource().Token, TaskContinuationOptions.None,
//This is to auto invoke back into the original thread
TaskScheduler.FromCurrentSynchronizationContext());
task2.ContinueWith((previousTask)=>
{
//Return back to the main thread
label1.Text += "The value of task2 is going to be 2-->"
+ previousTask.Result;
}
, new CancellationTokenSource().Token, TaskContinuationOptions.None,
//This is to auto invoke back into the original thread
TaskScheduler.FromCurrentSynchronizationContext());
Wenn Sie sich nicht um jeden einzelnen kümmern müssen, können Sie warten, bis sie alle zurückkommen:
var taskList = new List<Task>{task1,task2};
Task.Factory.ContinueWhenAll(taskList.ToArray(),
(tasks)=>
{
label1.Text = "Results are: ";
foreach(var task in tasks)
{
//process each task
label1.Text += task.Result + "|";
}
},
new CancellationTokenSource().Token, TaskContinuationOptions.None,
//This is to auto invoke back into the original thread
TaskScheduler.FromCurrentSynchronizationContext());