【发布时间】:2019-10-02 22:37:55
【问题描述】:
假设我有一些异步任务,有时运行得快有时慢,
public Random seed = new Random();
private async Task<string> _Work()
{
int time = seed.Next(0, 5000);
string result = string.Format("Worked for {0} milliseconds", time);
await Task.Delay(time);
return result;
}
public void SomeMethod()
{
_Work(); // starts immediately? Am I right?
// since _Work() will be executed immediately before ContinueWith() is executed,
// will there be a chance that callback will not be called if _Work completes very quickly,
// like before ContinueWith() can be scheduled?
_Work().ContinueWith(callback)
}
Task.ContinueWith()中的回调是否保证在上述场景中运行?
【问题讨论】:
-
如果
_Work很快完成,为什么你认为callback不会被调用? -
@EricLippert 是的,假设 SomeMethod() 在程序的另一部分被多次调用。
标签: c# async-await task