简体   繁体   English

等待同步方法时会发生什么

[英]What happens when you await a synchronous method

If I have a synchronous method "GetStrings()": 如果我有一个同步方法“GetStrings()”:

private static Task<string[]> GetStrings(IEnumerable<int> ids)
{
    var tasks = ids.Distinct().Select(GetString);
    return Task.WhenAll(tasks);
}

private static async Task<string> GetString(int stringId)
{
    await Task.Delay(15000);
    return "hello" + stringId;
}

(which itself calls async method "GetString()") (它本身称为异步方法“GetString()”)

And I call this synchronous "GetStrings()" method from an async method: 我从异步方法中调用这个同步 “GetStrings()”方法:

public static async Task Main()
{
    var ids = new List<int> { 1, 2, 3 };
    await GetStrings(ids);
    Console.WriteLine("all done");
    Console.ReadLine();
}

What would be the behavioural difference, if GetStrings( ) was actually async? 如果GetStrings( )实际上是异步的,那么行为差异会是什么? (and performed an await on the Task.WhenAll ) (并在Task.WhenAll上进行了等待)

Would it simply stop Task.WhenAll from blocking the thread? 它会简单地阻止Task.WhenAll阻止线程吗? I've found some production code which looks like this, so I've put together this small example to try and understand what's going. 我找到了一些看起来像这样的生产代码,所以我把这个小例子放在一起试着去了解发生了什么。 It's difficult to identify the difference though. 但是很难确定差异。

Task.WhenAll doesn't block anyway, unlike Task.WaitAll . Task.WhenAll不会阻塞,与Task.WaitAll不同。 It just return a task that completes when all of the original tasks have completed. 它只返回在所有原始任务完成时完成的任务。

It's important to understand that you don't await a method - you await a value (or some type that has to be awaitable). 重要的是要理解你没有等待一个方法 - 等待一个 (或某种必须等待的类型)。 The await mechanism doesn't care how you obtained that value. await机制并不关心你是如何获得该值的。

If GetStrings were async, there'd be one important difference: any exceptions thrown (eg if ids were null) would be result in a faulted task, whereas currently the exception would be thrown directly. 如果GetStrings是异步的,则会有一个重要的区别:抛出的任何异常(例如,如果ids为null)将导致出现故障,而当前异常将直接抛出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM