我有以下示例代码。问题是,Task
表示IsCompleted
,即使只是await
。
longTask
仅await
s(Task.Delay())尚未完成,为什么IsCompleted
为真? longTask
无法完成每个while(true)
,因为它会被static async Task Main(string[] args)
{
Task longTask = Task.Factory.StartNew(async () =>
{
while (true)
{
long count = 0;
Console.WriteLine("doing hard work.");
while (count < 99999999)
{
count++;
}
Console.WriteLine("wait for a moment");
await Task.Delay(1000);
Console.WriteLine("I have waited enough");
}
});
while (true)
{
Console.WriteLine($"status: {longTask.IsCompleted}");
await Task.Delay(100);
}
}
捕获?!
{{1}}
答案 0 :(得分:0)
如果您希望longTask
代表内部永不结束的任务,请使用适当的设置调用.Unwrap()
或使用具有合理默认值的Task.Run
:
public static class Program
{
static async Task Main(string[] args)
{
Task longTask = Task.Factory.StartNew(async () =>
{
while (true)
{
long count = 0;
Console.WriteLine("doing hard work.");
while (count < 99999999)
{
count++;
}
Console.WriteLine("wait for a moment");
await Task.Delay(1000);
Console.WriteLine("I have waited enough");
}
}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap();
while (true)
{
Console.WriteLine($"status: {longTask.IsCompleted}");
await Task.Delay(100);
}
}
}
或强>
public static class Program
{
static async Task Main(string[] args)
{
Task longTask = Task.Run(async () =>
{
while (true)
{
long count = 0;
Console.WriteLine("doing hard work.");
while (count < 99999999)
{
count++;
}
Console.WriteLine("wait for a moment");
await Task.Delay(1000);
Console.WriteLine("I have waited enough");
}
});
while (true)
{
Console.WriteLine($"status: {longTask.IsCompleted}");
await Task.Delay(100);
}
}
}
更多信息:MSDN&amp; Startnew is Dangerous