在此功能中等待做什么? [英] What does await do in this function?

查看:64
本文介绍了在此功能中等待做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我了解 C#中的 async-await 模式,但是今天我发现我确实不知道.

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

在这样的简单代码段中.我已经定义了 System.Net.ServicePointManager.DefaultConnectionLimit = 1000; .

In a simple code snippet like this. I have System.Net.ServicePointManager.DefaultConnectionLimit = 1000; defined already.

public static async Task Test()
{
    HttpClient client = new HttpClient();
    string str;
    for (int i = 1000; i <= 1100; i++)
        str = await client.GetStringAsync($"https://en.wikipedia.org/wiki/{i1}");
}

等待在这里做什么?最初,我以为这是异步等待模式,这意味着HttpClient基本上将以多线程方式启动所有HTTP GET调用,即基本上所有Urls都应立即获取.

What does await do here? Initially I thought since this is in async-await pattern, it means basically HttpClient will initiate all HTTP GET calls in a multi-threaded fashion, i.e. basically all the Urls should be fetched at once.

但是当我使用Fiddler分析行为时,我发现它确实按顺序获取URL.

But when I'm using Fiddler to analyze the behavior I've found it really fetches the URLs sequentially.

我需要对此进行更改以使其起作用:

I need to change it to this to make it work:

public static async Task<int> Test()
{
    int ret = 0;
    HttpClient client = new HttpClient();
    List<Task> taskList = new List<Task>();
    for (int i = 1000; i <= 1100; i++)
    {
        var i1 = i;
        var task = Task.Run(() => client.GetStringAsync($"https://en.wikipedia.org/wiki/{i1}"));
        taskList.Add(task);
    }
    Task.WaitAll(taskList.ToArray());
    return ret;
}

这次,URL是并行获取的.那么 await 关键字在第一个代码段中实际上是做什么的?

This time the URLs are fetched in parallel. So what does the await keyword really do in the first code snippet?

推荐答案

唤醒 完成HTTP请求.仅在每个单个请求完成后,代码才恢复( for 迭代...).

您的第二个版本之所以能够正常工作,是因为它不会等待每个任务完成,然后再启动以下任务,并且仅在所有任务启动后才等待完成.

Your 2nd version works precisely because it doesn't await for each task to complete before initiating the following tasks, and only waits for all the tasks to complete after all have been started.

async-await有用的是允许 calling 函数在等待异步函数的同时继续做其他事情,这与阻塞调用函数的同步(正常")函数相反,完成.

What async-await is useful for is allowing the calling function to continue doing other things while the asynchronous function is awaiting, as opposed to synchronous ("normal") functions that block the calling function until completion.

这篇关于在此功能中等待做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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