What does await do in this function?

后端 未结 3 1870
谎友^
谎友^ 2021-01-19 03:49

I thought I understand the async-await pattern in C# but today I\'ve found out I really do not.

In a simple code snippet like this. I have

3条回答
  •  醉梦人生
    2021-01-19 04:04

    Per the msdn documentation

    The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work.

    That means the await operator blocks the execution of the for loop until it get a responds from the server, making it sequential.

    What you can do is create all the task (so that it begins execution) and then await all of them.

    Here's an example from another StackOverflow question

    public IEnumerable DownloadContentFromUrls(IEnumerable urls)
    {
        var queue = new ConcurrentQueue();
    
        using (var client = new HttpClient())
        {
            Task.WaitAll(urls.Select(url =>
            {
                return client.GetAsync(url).ContinueWith(response =>
                {
                    var content = JsonConvert.
                        DeserializeObject>(
                            response.Result.Content.ReadAsStringAsync().Result);
    
                    foreach (var c in content)
                        queue.Enqueue(c);
                });
            }).ToArray());
        }
    
        return queue;
    }
    

    There's also good article in msdn that explains how to make parallel request with await.

    Edit:

    As @GaryMcLeanHall pointed out in a comment, you can change Task.WaitAll to await Task.WhenAll and add the async modifier to make the method return asynchronously

    Here's another msdn article that picks the example in the first one and adds the use of WhenAll.

提交回复
热议问题