我正在寻找出路运行多项任务并报告任务状态而不是顺序。 在这里,我粘贴了一个代码,其中多个任务在所有任务完成时运行和报告。
var task1 = Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
return "dummy value 1";
});
var task2 = Task.Factory.StartNew(() =>
{
Thread.Sleep(13000);
return "dummy value 2";
});
var task3 = Task.Factory.StartNew(() =>
{
Thread.Sleep(2000);
return "dummy value 3";
});
Task.Factory.ContinueWhenAll(new[] { task1, task2, task3 }, tasks =>
{
foreach (Task<string> task in tasks)
{
Console.WriteLine(task.Result);
}
});
Console.ReadLine();
task1将花费更少的时间,然后task3将完成,最后一个task2将完成,但ContinueWhenAll
始终显示task1已完成,然后task2&amp; TASK3。我想以这样的方式修改代码,结果是哪个任务快速完成,首先不按顺序显示。在哪里改变代码。请指导。感谢
var taskp = Task.Factory.StartNew(() =>
{
var task1 = Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
return "Task1 finished";
}).ContinueWith((continuation) => { Console.WriteLine(continuation.Result); });
var task2 = Task.Factory.StartNew(() =>
{
Thread.Sleep(3000);
return "Task2 finished";
}).ContinueWith((continuation) => { Console.WriteLine(continuation.Result); });
var task3 = Task.Factory.StartNew(() =>
{
Thread.Sleep(2000);
return "Task3 finished";
}).ContinueWith((continuation) => { Console.WriteLine(continuation.Result); });
return "Main Task finished";
});
taskp.ContinueWith(t => Console.WriteLine(t.Result));
Console.ReadLine();
答案 0 :(得分:1)
一个简单的解决方案是单独ContinueWith
每项任务。这是一个非常快速和肮脏的例子:
var taskp = Task.Factory.StartNew(() =>
{
var task1 = Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
return "dummy value 1";
}).ContinueWith((continuation) => { Console.WriteLine("task1"); });
var task2 = Task.Factory.StartNew(() =>
{
Thread.Sleep(3000);
return "dummy value 2";
}).ContinueWith((continuation) => { Console.WriteLine("task2"); });
var task3 = Task.Factory.StartNew(() =>
{
Thread.Sleep(2000);
return "dummy value 3";
}).ContinueWith((continuation) => { Console.WriteLine("task3"); });
Task.Factory.ContinueWhenAll(new Task[] { task1, task2, task3}, (x) => { Console.WriteLine("Main Task Complete"); });
});
更新代码以适应OP的UPDATE,其中“Main”任务将在所有“内部”任务完成后输出。为了使它taskp
返回字符串而不是写它,代码变为
var taskp = Task.Factory.StartNew<string>(() =>
{
var task1 = ...; //same
var task2 = ...; //same
var task3 = ...; //same
return "Main Task Complete";
}).ContinueWith((x)=> Console.WriteLine(x.Result));
必须使用StartNew<>
重载来指定Task
拥有Result
的返回类型。