本文介绍了C#异步awaitable澄清?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里读是:

等待检查该 awaitable 以查看是否有完成;如果
  该awaitable已经完成,则该方法只是继续
  运行(同步,就像一个普通的方法)。

什么?

当然,这将无法完成,因为它甚至还没有开始!

Of course it won't be completed because it hasn't even started !

例如:

public async Task DoSomethingAsync()
{
  await DoSomething();
}

下面的await 检查awaitable,看它是否已经完成
(根据文章),但它(的DoSomething)的没有事件开始呢! ,所以结果会的总是的是

Here await examines the awaitable to see if it has already completed(according to the article) , but it (DoSomething) haven't event started yet ! , so the result will always be false

这将使SENCE,如果文章是说:

It would make sence if the article was to say :

等待检查该awaitable,看它是否有完成
  在 X MS; (超时)

我可能失去了一些东西在这里..

I probably missing something here..

推荐答案

考虑这个例子:

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;
}

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

Now imagine calling that within another async method:

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

由于缓存的 -

这是的完全的可能任务由 GetProfileAsync返回将已经用该方法返回的时间内完成。或者你可以等待,当然不是异步方法的结果以外的东西。

It's entirely possible that the task returned by GetProfileAsync will already have completed by the time the method returns - because of the cache. Or you could be awaiting something other than the result of an async method, of course.

所以,不,你的主张,即awaitable将不会被你等待它的时间内完成是不正确的。

So no, your claim that the awaitable won't have completed by the time you await it isn't true.

有其他的原因了。考虑这个code:

There are other reasons, too. Consider this code:

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 的第二个任务,它将完成,您只需继续下去

It's possible that the second task will complete before the first one - in which case by the time you await the second task, it will have completed and you can just keep going.

这篇关于C#异步awaitable澄清?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:45