C#异步等待澄清?

Roy*_*mir 3 c# async-await c#-5.0 .net-4.5

我在这里读到:

静候检awaitable,看它是否已经完成; 如果等待已经完成,那么该方法就会继续运行(同步,就像常规方法一样).

什么 ?

当然它还没有完成,因为它还没有开始!

例如:

public async Task DoSomethingAsync()
{ 
  await DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

这里await检查awaitable,看它是否已经(根据文章)已经完成,但它(DoSomething的)没有事件开始呢!,结果将永远如此false

如果文章要说:

Await检查是否等待,以确定它是否xms 内完成 ; (超时)

我可能在这里遗漏了什么......

Jon*_*eet 13

考虑这个例子:

public async Task<UserProfile> 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;
}
Run Code Online (Sandbox Code Playgroud)

现在想象一下在另一个异步方法中调用它:

public async Task<...> DoSomething(Guid userId)
{
    // First get the profile...
    UserProfile profile = await GetProfileAsync(userId);
    // Now do something more useful with it...
}
Run Code Online (Sandbox Code Playgroud)

这是完全可能的,通过返回的任务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
}
Run Code Online (Sandbox Code Playgroud)

第二个任务可能在第一个任务之前完成 - 在这种情况下,当你等待第二个任务时,它将完成,你可以继续前进.