none
Calling API asynchronously RRS feed

  • Question

  • I need to call a API 5000 times, Presently with the current logic its happening synchronously one by one. Is there any way to call it asynchronously without actually waiting for the API response. Code Below.  

    public void CallAPI()
            {            try   {
                    
                    while (true)
                    {                 
                        using (HttpClient httpclient = new HttpClient())
                        {// Want to call the API Asynchronously
                            for (int i = 0; i < 5000; i++)
                            {
                                DateTime dt = DateTime.Now;
                                dt = dt.AddSeconds(-dt.Second);
                                Log[] data1 = new Log[]
                            {                           
                                log =new Log(){LogID=Guid.NewGuid(),LogLevel=new LogLevel(){ },Message="Maverick_Messgaes",Source="Maverick",StackTrace="Maverick Started",
                                 Time=dt,Traceid="1"},
                        };
                                var response4 = httpclient.PostAsJsonAsync("http://localhost:8095/api/Log/PostAsync", data1).Result;
                            }

                        }
                        //logstack.Clear();
                        Console.WriteLine(log.Message + log.Time + " ");
                        Thread.Sleep(120000);
                        Console.WriteLine("  " + " 5000 messages Sent.. Iterating Again" + "" + DateTime.Now.ToString());

                    }
                }
                catch(Exception ex)
                { throw ex; }

            }

    Thursday, March 8, 2018 9:43 AM

All replies

  • You are getting the Result property of the task returned by PostAsJsonAscyn. This will cause the calling code to wait on the thread for the result.

    But you don't seem to be doing anything with this result anyway (just putting it in a response4 variable). So if you don't need this, don't get the result

    httpclient.PostAsJsonAsync("http://localhost:8095/api/Log/PostAsync", data1);

    If you may want the results afterwards, then you can get the Task returned by PostAsJsonAsync and stick it in a list, then after the loop do a Task.WaitAll() call to wait for all the tasks to complete before examining their results.

    Thursday, March 8, 2018 9:52 AM
  • I assume you should throttle (limit) the number of posts being done in parallel. I am not sure but I think HttpClient will limit the number done and you might be able to increase that. Even if you can increase the number it does, you should limit the number you queue up. If you do then you can do as RJP1973 suggests except use WaitAny instead of WaitAll and when one of them completes queue up (do) another one until there are no more.

    There is no need for Sleep. Use a wait as described instead.



    Sam Hobbs
    SimpleSamples.Info

    Thursday, March 8, 2018 9:17 PM
  • Hello Kumar,

    Try to use Parallel.For  instead of for statement. The method may run in parallel based on internal algorithm and it could use less time to execute code than synchronous.

          Parallel.For(0, 5000, (r) => {
              ...
          });

    And if you want to test server performance, you could use third party software to fire a number of requests each second.

    Best way to stress test a website

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, March 9, 2018 6:22 AM
    Moderator