如何确定何时完成所有任务 [英] How to determine when all task is completed
问题描述
下面是示例代码启动多个任务
Task.Factory.StartNew(()=>
{
//的foreach(KeyValuePair<字符串,字符串>在dicList项)
Parallel.ForEach(dicList,
项=>
{
//创建和UI线程
VAR ucProgress =(进展)fpPanel.Invoke(createProgress,进入)添加进展;
//执行ucProgress.Process();在并行
非UI线程//将.Process();必须使用*调用
ucProgress.Process()更新UI;
System.Threading.Thread .SpinWait(5000000);
});
});
.ContinueWith(任务=>
{
//处理异常使用task.Exception成员
VAR进度=(进度)task.AsyncState;
如果(!task.IsCancelled)
{
//隐藏进度条在这里和复位pb.Value = 0
}
},
TaskScheduler.FromCurrentSynchronizationContext(从UI线程
)//更新UI);
当我们开始使用多任务 Task.Factory.StartNew()
然后我们可以使用 .ContinueWith()
块,以确定每个任务完成时。我的意思是每个任务完成ContinueWith块火一次。所以我只是想知道的是有没有TPL库的机制。如果我开始使用10任务 Task.Factory.StartNew()
让我怎么当10的任务是完成后通知。请给一些有识之士与示例代码。
如果我使用Task.Factory启动10个任务。 StartNew()让我怎么通知时,10的任务是完成
块引用>
三个选项后:
- 阻塞
Task.WaitAll
打电话,当所有给定的任务已经完成,只返回
- 异步的
Task.WhenAll
调用,它返回时完成所有任务给定的任务已经完成。 (介绍了在.NET 4.5。)
TaskFactory.ContinueWhenAll
,这增加了在所有给定的任务已经完成,这将运行延续任务。
here is sample code for starting multiple task
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 );
when we start multiple task using
Task.Factory.StartNew()
then we can use.ContinueWith()
block to determine when each task finish. i mean ContinueWith block fire once for each task completion. so i just want to know is there any mechanism in TPL library. if i start 10 task usingTask.Factory.StartNew()
so how do i notify after when 10 task will be finish. please give some insight with sample code.解决方案if i start 10 task using Task.Factory.StartNew() so how do i notify after when 10 task will be finish
Three options:
- The blocking
Task.WaitAll
call, which only returns when all the given tasks have completed- The async
Task.WhenAll
call, which returns a task which completes when all the given tasks have completed. (Introduced in .NET 4.5.)TaskFactory.ContinueWhenAll
, which adds a continuation task which will run when all the given tasks have completed.这篇关于如何确定何时完成所有任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!