如果您使用的是.NET 4.0+,那麼您可以使用TPL。該守則將是這個樣子:
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());
如果你不需要處理每一個,因爲他們進來,那麼你可以等到他們全部返回:
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());
您使用的是什麼版本的.NET? – 2012-02-28 21:20:15
哪個版本的.Net?如果V4 +,您可以使用非常容易使用的Task類。 – 2012-02-28 21:20:29
完成工作後返回工作人員並加入主題。 – CodeCaster 2012-02-28 21:20:32