Tho*_*mas 9 c# task-parallel-library
这是启动多个任务的示例代码
Task.Factory.StartNew(() =>
{
//foreach (KeyValuePair<string, string> entry in dicList)
Parallel.ForEach(dicList,
entry =>
{
//create and add the Progress in UI thread
var ucProgress = (Progress)fpPanel.Invoke(createProgress, entry);
//execute ucProgress.Process(); in non-UI thread in parallel.
//the .Process(); must update UI by using *Invoke
ucProgress.Process();
System.Threading.Thread.SpinWait(5000000);
});
});
.ContinueWith(task =>
{
//to handle exceptions use task.Exception member
var progressBar = (ProgressBar)task.AsyncState;
if (!task.IsCancelled)
{
//hide progress bar here and reset pb.Value = 0
}
},
TaskScheduler.FromCurrentSynchronizationContext() //update UI from UI thread
);
Run Code Online (Sandbox Code Playgroud)
当我们使用Task.Factory.StartNew()then 启动多个任务时,我们可以使用.ContinueWith()block来确定每个任务何时完成.我的意思是每次任务完成后,ContinueWith会阻止一次.所以我只想知道TPL库中是否有任何机制.如果我开始使用10个任务,Task.Factory.StartNew()那么在10个任务完成后如何通知我.请提供示例代码的一些见解.
Jon*_*eet 23
如果我使用Task.Factory.StartNew()启动10个任务,那么如何在10个任务完成后通知
三种选择:
Task.WaitAll调用,仅在所有给定任务完成时返回Task.WhenAll调用,返回在所有给定任务完成时完成的任务.(在.NET 4.5中引入.)TaskFactory.ContinueWhenAll,它会添加一个继续任务,该任务将在所有给定任务完成后运行.| 归档时间: |
|
| 查看次数: |
16608 次 |
| 最近记录: |