这里是启动多任务的示例代码
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
);
当我们使用 Task.Factory.StartNew()
启动多个任务时,我们可以使用 .ContinueWith()
block 来确定每个任务何时完成。我的意思是 ContinueWith 每次任务完成时都会触发一次。所以我只想知道 TPL 库中是否有任何机制。如果我使用 Task.Factory.StartNew()
开始 10 个任务,那么我如何在 10 个任务完成后通知。请用示例代码给出一些见解。
最佳答案
if i start 10 task using Task.Factory.StartNew() so how do i notify after when 10 task will be finish
三个选项:
- 阻塞
Task.WaitAll
调用,仅在所有给定任务完成后返回 - 异步
Task.WhenAll
调用,它返回一个任务,该任务在所有给定任务完成时完成。 (在 .NET 4.5 中引入。) -
TaskFactory.ContinueWhenAll
,它添加了一个持续任务,该任务将在所有给定任务完成后运行。
关于c# - 如何确定所有任务何时完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17021701/