C#异步等待澄清?
我在这里读到:
等待检查等待它是否已经完成; 如果等待已经完成,那么该方法就会继续运行(同步,就像常规方法一样)。
什么 ?
当然它还没有完成,因为它还没有开始!
例子:
public async Task DoSomethingAsync() { await DoSomething(); }
在这里await
检查await
它是否已经完成(根据文章),但它(DoSomething)尚未开始活动! ,结果总是 false
如果文章要说:
Await检查等待是否已经在
x
毫秒内完成; (超时)
我可能在这里错过了什么..
考虑这个例子:
public async Task GetProfileAsync(Guid userId) { // First check the cache UserProfile cached; if (profileCache.TryGetValue(userId, out cached)) { return cached; } // Nope, we'll have to ask a web service to load it... UserProfile profile = await webService.FetchProfileAsync(userId); profileCache[userId] = profile; return profile; }
现在想象一下在另一个异步方法中调用它:
public async Task<...> DoSomething(Guid userId) { // First get the profile... UserProfile profile = await GetProfileAsync(userId); // Now do something more useful with it... }
GetProfileAsync
返回的任务完全有可能在方法返回时已经完成 – 因为缓存。 或者你当然可以等待异步方法的结果。
所以不,你在等待它时等待它的说法是不正确的。
还有其他原因。 考虑以下代码:
public async Task<...> DoTwoThings() { // Start both tasks... var firstTask = DoSomethingAsync(); var secondTask = DoSomethingElseAsync(); var firstResult = await firstTask; var secondResult = await secondTask; // Do something with firstResult and secondResult }
第二个任务可能在第一个任务之前完成 – 在这种情况下,当你等待第二个任务时,它将完成,你可以继续前进。
await可以执行任何Task
或Task
, 包括已完成的任务 。
在您的示例中,内部DoSomething()
方法(应该更名为DoSomethingAsync()
及其调用方DoSomethingElseAsync()
)返回Task
(或Task
)。 该任务可以是从其他地方获取的已完成任务,该方法不需要启动自己的任务。