C#异步等待澄清? [英] C# async awaitable clarification?

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

问题描述

我读过此处:

Await 检查 awaitable 是否已经完成;如果awaitable 已经完成,然后该方法继续运行(同步,就像常规方法一样).

Await examines that awaitable to see if it has already completed; if the awaitable has already completed, then the method just continues running (synchronously, just like a regular method).

什么?

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

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

示例:

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

这里await检查awaitable是否已经完成(根据文章),但它(DoSomething)还没有活动开始!,所以结果将总是false

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

如果文章要说:

Await 检查等待对象是否已经完成x 毫秒内;(超时)

Await examines that awaitable to see if it has already completed within x ms; (timeout)

我可能在这里遗漏了一些东西..

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.

所以不,您声称等待对象在等待时不会完成是不正确的.

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

还有其他原因.考虑这个代码:

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
}

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

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#异步等待澄清?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆