在以下代码中:
async static Task<int> test(){
Console.WriteLine("{0}: Start 3", DateTime.Now);
await Task.Delay(3000);
return 3;
}
List<Task<int>> tasks2 = new List<Task<int>> {
test(),
new Task<int>( delegate { Console.WriteLine("{0}: Start 3", DateTime.Now); Task.Delay(3000).Wait(); return 3; } ),
new Task<int>( delegate { Console.WriteLine("{0}: Start 1", DateTime.Now); Task.Delay(1000).Wait(); return 1; } ),
};
foreach (var task in tasks2)
task.Start(); // this cause exception at runtime
为什么我不能将test
方法用作Task<int>
?如果函数返回Task<int>
...
答案 0 :(得分:3)
The task returned by test()
has already started when you invoked test()
. So you cannot start it again.
Actually, the task returned by test()
is a promise-style task that does not run on the thread-pool thread in the first place.
You should almost always create tasks that have already started (once they are created).
I.e., you should not use the constructor of Task
and then call the Start
method.
Instead, if you want to run the task on a thread-pool thread, use Task.Run
。
答案 1 :(得分:0)
正如其他人所说,你不能打电话给Start
,因为它已经开始了。如果这是您想要的状态,您仍然可以通过检查状态来实现目标。请参阅以下更新的代码:
async static Task<int> test(){
Console.WriteLine("{0}: Start 3", DateTime.Now);
await Task.Delay(3000);
return 3;
}
List<Task<int>> tasks2 = new List<Task<int>> {
new Task<int>( delegate{ return test().Result;}),
new Task<int>( delegate { Console.WriteLine("{0}: Start 3", DateTime.Now); Task.Delay(3000).Wait(); return 3; } ),
new Task<int>( delegate { Console.WriteLine("{0}: Start 1", DateTime.Now); Task.Delay(1000).Wait(); return 1; } ),
};
foreach (var task in tasks2)
{
task.Start();
}
答案 2 :(得分:0)
正如其他人所指出的那样,当您致电test()
时,任务已经启动,因此您无法再次启动它。给下面的代码一个镜头,看看发生了什么。
如您所见,控制台输出适用于每项任务。 test()
返回的任务是通过调用该方法启动的。因此,此代码仅显式启动处于Created
状态的其他任务。最后,我们通过调用WhenAll()
等待所有任务完成,而public static class AsyncTest
{
static async Task<int> test()
{
Console.WriteLine("{0}: Start 3", DateTime.Now);
await Task.Delay(3000);
return 3;
}
public static void Main()
{
var tasks2 = new List<Task<int>>
{
test(),
new Task<int>( delegate { Console.WriteLine("{0}: Start 3", DateTime.Now); Task.Delay(3000).Wait(); return 3; } ),
new Task<int>( delegate { Console.WriteLine("{0}: Start 1", DateTime.Now); Task.Delay(1000).Wait(); return 1; } )
};
foreach (var task in tasks2)
{
if (task.Status == TaskStatus.Created)
task.Start();
}
Task.WhenAll(tasks2).Wait();
Console.WriteLine("All done!");
}
}
又返回我们等待的任务。你会注意到“All done!”之前最长的3秒延迟(所有任务)打印出来。
usage="blah"
while [ "$1" != "" ]; do
case $1 in
-arg1 ) shift
arg1=$1
;;
-arg2 ) shift
arg2=$1
;;
* ) echo $usage
exit 1
esac
shift
done
find . -name "*.ext" -exec bash -c 'command "$0" arg1="${arg1:-default}" arg2=${arg2:-default}' "{}" \+