locked
How to execute parallel tasks in Web API. RRS feed

  • Question

  • User-1571110992 posted

    Hi All,

    I have Web API  which included several functions. Each function making another API cal and creating chart object. How I can execute all inner function at once and wait until all task completed.   

     public Chart GetAllData([FromBody]ChartParam s)
            {
    int a =10 QueryDataIndicatorData(a); QueryGetAccess(); return Charttemp; }

    Wednesday, August 8, 2018 9:11 PM

Answers

  • User1724605321 posted

    Hi vishabedre,

    You can create and start the tasks , in each task you can make a call to API to get the response , await each task and finally return the final result in web api . Code below is for your reference :

            // GET api/values
            public async Task<IEnumerable<string>> GetAsync()
            {
                await CreateMultipleTasksAsync();
                return new string[] { "value1", "value2" };
            }
            private async Task CreateMultipleTasksAsync()
            {
                // Declare an HttpClient object, and increase the buffer size. The  
                // default buffer size is 65,536.  
                HttpClient client =
                    new HttpClient() { MaxResponseContentBufferSize = 1000000 };
    
                // Create and start the tasks. As each task finishes, DisplayResults   
                // displays its length.  
                Task<int> download1 =
                    ProcessURLAsync("http://msdn.microsoft.com", client);
                Task<int> download2 =
                    ProcessURLAsync("http://msdn.microsoft.com/library/hh156528(VS.110).aspx", client);
                Task<int> download3 =
                    ProcessURLAsync("http://msdn.microsoft.com/library/67w7t67f.aspx", client);
    
                // Await each task.  
                int length1 = await download1;
                int length2 = await download2;
                int length3 = await download3;
    
                int total = length1 + length2 + length3;
    
                // Display the total count for the downloaded websites.  
              var result =
                    string.Format("\r\n\r\nTotal bytes returned:  {0}\r\n", total);
            }
    
            async Task<int> ProcessURLAsync(string url, HttpClient client)
            {
                var byteArray = await client.GetByteArrayAsync(url);
                DisplayResults(url, byteArray);
                return byteArray.Length;
            }
    
            private void DisplayResults(string url, byte[] content)
            {
                // Display the length of each website. The string format   
                // is designed to be used with a monospaced font, such as  
                // Lucida Console or Global Monospace.  
                var bytes = content.Length;
                // Strip off the "http://".  
                var displayURL = url.Replace("http://", "");
                var result= string.Format("\n{0,-58} {1,8}", displayURL, bytes);
            }

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 9, 2018 6:22 AM
  • User1881638666 posted

    Hi,

    Use await Task.WhenAll

    https://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenall(v=vs.110).aspx

    Thanks,

    Wenushka

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 9, 2018 2:51 PM
  • User-1571110992 posted
    public async Task<Chart> GetAllDataPart2([FromBody]ChartParam s)
            {
                var tasks = new List<Task>();
                tasks.Add(Task.Run(() => QueryDataCDCPopular(Convert.ToDateTime(s.start_period.Value), Convert.ToDateTime(s.end_period.Value))));
                tasks.Add(Task.Run(() => QueryTeachingResourcesData(Convert.ToDateTime(s.start_period.Value), Convert.ToDateTime(s.end_period.Value))));
             
    
                await Task.WhenAll(tasks);
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 9, 2018 9:54 PM

All replies

  • User1724605321 posted

    Hi vishabedre,

    You can create and start the tasks , in each task you can make a call to API to get the response , await each task and finally return the final result in web api . Code below is for your reference :

            // GET api/values
            public async Task<IEnumerable<string>> GetAsync()
            {
                await CreateMultipleTasksAsync();
                return new string[] { "value1", "value2" };
            }
            private async Task CreateMultipleTasksAsync()
            {
                // Declare an HttpClient object, and increase the buffer size. The  
                // default buffer size is 65,536.  
                HttpClient client =
                    new HttpClient() { MaxResponseContentBufferSize = 1000000 };
    
                // Create and start the tasks. As each task finishes, DisplayResults   
                // displays its length.  
                Task<int> download1 =
                    ProcessURLAsync("http://msdn.microsoft.com", client);
                Task<int> download2 =
                    ProcessURLAsync("http://msdn.microsoft.com/library/hh156528(VS.110).aspx", client);
                Task<int> download3 =
                    ProcessURLAsync("http://msdn.microsoft.com/library/67w7t67f.aspx", client);
    
                // Await each task.  
                int length1 = await download1;
                int length2 = await download2;
                int length3 = await download3;
    
                int total = length1 + length2 + length3;
    
                // Display the total count for the downloaded websites.  
              var result =
                    string.Format("\r\n\r\nTotal bytes returned:  {0}\r\n", total);
            }
    
            async Task<int> ProcessURLAsync(string url, HttpClient client)
            {
                var byteArray = await client.GetByteArrayAsync(url);
                DisplayResults(url, byteArray);
                return byteArray.Length;
            }
    
            private void DisplayResults(string url, byte[] content)
            {
                // Display the length of each website. The string format   
                // is designed to be used with a monospaced font, such as  
                // Lucida Console or Global Monospace.  
                var bytes = content.Length;
                // Strip off the "http://".  
                var displayURL = url.Replace("http://", "");
                var result= string.Format("\n{0,-58} {1,8}", displayURL, bytes);
            }

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 9, 2018 6:22 AM
  • User-1571110992 posted

    Thank you for Replay. I just want to execute this two function parallel. And want to make sure both execute successfully before returning output form API.  

     QueryDataIndicatorData(a);
     QueryGetAccess();


     

    Thursday, August 9, 2018 2:18 PM
  • User1881638666 posted

    Hi,

    Use await Task.WhenAll

    https://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenall(v=vs.110).aspx

    Thanks,

    Wenushka

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 9, 2018 2:51 PM
  • User-1571110992 posted
    public async Task<Chart> GetAllDataPart2([FromBody]ChartParam s)
            {
                var tasks = new List<Task>();
                tasks.Add(Task.Run(() => QueryDataCDCPopular(Convert.ToDateTime(s.start_period.Value), Convert.ToDateTime(s.end_period.Value))));
                tasks.Add(Task.Run(() => QueryTeachingResourcesData(Convert.ToDateTime(s.start_period.Value), Convert.ToDateTime(s.end_period.Value))));
             
    
                await Task.WhenAll(tasks);
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 9, 2018 9:54 PM