[英]C# Task.Run does not await action variable
请参阅示例代码。
Console.WriteLine("start")
Task.Run(async () =>
{
await Task.Delay(3000);
});
Console.WriteLine("end");
// result
// start [3s delay] end
有用! 但下面的代码不起作用。
Action action = async () =>
{
await Task.Delay(3000);
};
Console.WriteLine("start")
Task.Run(action);
Console.WriteLine("end");
// result
// start [without delay] end
为什么Task.Run
不等待异步操作变量?
编辑 - - - - - - - - - - - - -
我很抱歉。 我写错了代码。 这是正确的代码。
我在 VS 2017 的 C# Interactive 上测试过
Console.WriteLine("start");
await Task.Run(async () =>
{
await Task.Delay(3000);
});
Console.WriteLine("end");
Action action = async () =>
{
await Task.Delay(3000);
};
Console.WriteLine("start");
await Task.Run(action);
Console.WriteLine("end");
使用 async 和 Tasks 的主要原因是让两个或多个方法同时运行。 因此,您的方法将继续运行,并且在延迟完成后,将在延迟后调用任何内容,因为您在任务中运行另一个异步函数。
如果你运行这个方法,你会注意到
完成的
将打印在其他工作的中间(这里的其他工作是for loop
,
Console.WriteLine("start");
Task.Run(async () =>
{
await Task.Delay(200);
Console.WriteLine("Finished");
});
for(int i = 0; i < 500; i++)
{
Console.WriteLine(i);
}
Console.WriteLine("end");
Console.ReadKey();
出于某种原因,它在 dotnetfiddle 上无法按预期工作
即使您没有在任务中运行 async,它们也会同时运行。
看看这个例子:
Console.WriteLine("start");
Task.Run(() =>
{
Task.Delay(2000).Wait(); // Will NOT wait !
Console.WriteLine("Finished");
});
for(int i = 0; i < 500; i++)
{
Console.WriteLine(i);
}
Console.WriteLine("end");
Console.ReadKey();
因为它在任务中,所以它会毫不拖延地继续
但是如果你想让方法等待,首先:不要在任务上运行它。 第二:调用Wait() 方法。
喜欢 :
Console.WriteLine("start");
Task.Delay(2000).Wait(); // It'll wait for 2 seconds before continue.
for(int i = 0; i < 500; i++)
{
Console.WriteLine(i);
}
Console.WriteLine("end");
Console.ReadKey();
在没有等待的情况下使用Task.Run
,这只会“触发并忘记”。 代码执行不会等待它,它会在thread pool
的thread
可用时立即运行它。
通常,如果您想卸载一些工作并等待该工作完成,请创建一个返回Task
的单独方法,然后await
它。
示例:
Console.WriteLine("start")
await DoWorkAsync();
Console.WriteLine("end");
/////////
private Task DoWorkAsync()
{
return Task.Run(async () =>
{
await Task.Delay(3000);
});
}
请注意,不建议将方法主体包装到Task
并返回它,这通常会导致一些代码异味。
Stephen Cleary 有关于Tasks
和async/await
很好的信息。 我会读到这个:
会像这样工作,虽然不是那么明显:
Func<Task> action = async () =>
{
await Task.Delay(3000);
};
Console.WriteLine("start");
await Task.Run(action);
Console.WriteLine("end");
你可以试试这个:
Action action = async () =>
{
await Task.Delay(3000);
};
Console.WriteLine("start");
Task.Run(action).Wait();
Console.WriteLine("end");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.