简体   繁体   中英

How to Optimize C# Async Calls

I am new to the async world of C# and admittedly don't have a lot of knowledge on the subject. I just had to implement it in one of our services and I am a little confused on how it works. I want to POST to an API as fast as absolutely possible. I'm less interested in how long it takes to get the response and do stuff with it. Here's an example of what I'm doing.

        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();
    }

What happens is if I put 1000 items in the list, "Posted" is logged 1000 times immediately. Great, the process is done and can continue doing other things. The problem is the somewhere in the background the callPostFunction is calling postToAPI and posting to the API, it works, but it takes a long time. It takes about as long (although not as long) as it did before implementing async. I feel like I'm missing something.

I have to hit the API as fast. Ideally I'd like to hit it as often as the callPostFunction is getting called, nearly immediately. How might I go about doing that?

You're not missing something. It takes time to post a bunch of data. Network connections are slow. They have limited bandwidth. Doing this work asynchronously is no magic bullet for speed. It's purpose is not to optimize speed either.

Set ServicePointManager.DefaultConnectionLimit to int.MaxValue .

Also, as @Servy pointed out, avoid async void .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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