如何优化 C# 异步调用

KJ3*_*KJ3 2 c# api rest asynchronous async-await

我是 C# 异步世界的新手,不可否认,我对这个主题没有很多了解。我只需要在我们的一项服务中实施它,我对它的工作方式有点困惑。我想尽可能快地发布到 API。我对获得响应并用它做事需要多长时间不太感兴趣。这是我正在做的一个例子。

        foreach (var item in list)
        {
            callPostFunction(item.data);
            log("Posted");
        }

    public async void callPostFunction(PostData data)
    {
        var apiResult = await postToAPI(data);
        updateDB(apiResult);
    }

    public static async Task<string> postToAPI(PostData dataToSend)
    {
        var url = "Example.com";

        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = dataToSend;
        byte[] dataBytes = encoding.GetBytes(postData);

        httpWReq.Method = "POST";
        httpWReq.ContentType = "application/x-www-form-urlencoded";
        httpWReq.ContentLength = dataBytes.Length;
        httpWReq.Accept = "application/json, application/xml, text/json, text/x-json, text/javascript, text/xml";

        using (var stream = await httpWReq.GetRequestStreamAsync())
        {
            await stream.WriteAsync(dataBytes, 0, dataBytes.Length);
        }

        HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();

        return new StreamReader(response.GetResponseStream()).ReadToEnd();
    }
Run Code Online (Sandbox Code Playgroud)

如果我在列表中放入 1000 个项目,会发生什么情况,“已发布”会立即被记录 1000 次。太好了,过程已经完成,可以继续做其他事情了。问题是 callPostFunction 在后台某个地方调用 postToAPI 并发布到 API,它可以工作,但需要很长时间。它花费的时间与实现异步之前一样长(虽然没有那么长)。我觉得我错过了一些东西。

我必须尽快点击 API。理想情况下,我想在 callPostFunction 被调用时经常点击它,几乎立即。我该怎么做呢?

Ste*_*ary 5

设置ServicePointManager.DefaultConnectionLimitint.MaxValue

另外,正如@Servy 指出的那样,避免async void.