为什么第二个标题是按行开始的
var finalTask = parent.ContinueWith( .. )
不是在等待第一个线程结束吗?这是证明新线程没有等待第一个线程结束的打印输出:
Starting main thread 1
Starting ContinueWith thread 2
0 0 0
Ending ContinueWith thread 2
ContinueWith thread is finished!
Starting child thread 3
Ends child thread 3
Starting child thread 2
Ends child thread 2
Starting child thread 1
Ends child thread 1
代码:
public static void AttachTasksToMain()
{
Task<Int32[]> parent = Task.Run(() =>
{
Console.WriteLine("Starting main thread 1");
var results = new Int32[3];
new Task(() => {
Console.WriteLine("Starting child thread 1");
results[0] = 0;
Console.WriteLine("Ends child thread 1");
}, TaskCreationOptions.AttachedToParent).Start();
new Task(() => {
Console.WriteLine("Starting child thread 2");
results[1] = 1;
Console.WriteLine("Ends child thread 2");
}, TaskCreationOptions.AttachedToParent).Start();
new Task(() => {
Console.WriteLine("Starting child thread 3");
results[2] = 2;
Console.WriteLine("Ends child thread 3");
}, TaskCreationOptions.AttachedToParent).Start();
//this thread finishes when all child-thread are finished!
return results;
});
//parent.Wait();
var finalTask = parent.ContinueWith(parentTask =>
{
Console.WriteLine("Starting ContinueWith thread 2");
foreach (int i in parentTask.Result)
Console.WriteLine(i);
Console.WriteLine("Ending ContinueWith thread 2");
});
finalTask.Wait();
Console.WriteLine("ContinueWith thread is finished!");
}
最佳答案
问题是Task.Run
。这将使用 TaskCreationOptions.DenyChildAttach
启动任务。
使用 Task.Factory.StartNew
进行简单更改即可解决问题。这是因为这里的默认值是 TaskCreationOptions.None
。
See here深入讨论差异。
关于c# - 为什么具有ContinueWith选项的第二个线程不等待第一个线程的结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30138699/