Avatar of Jesper Christensen
Jesper Christensen

asked on 

c# asynchronous in loop

How to update a api Async?

Hi guys. I have a list of products and walts to update each product async
 foreach (var product in productlist)
{
    UpdateProduct(product);
   console.log(${product.productnumber} DONE);
}
How is this asynchronous ?
C#

Avatar of undefined
Last Comment
ste5an
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Simple answer that is asynchronous ONLY if the UpdatePoduct function uses some method inside it to make it asynchronous.  (eg. starts a thread, uses an async call...)
Avatar of Jesper Christensen
Jesper Christensen

ASKER

Yes, but how does I start a thread.
UpdateProduct() takes arround 2 seconds, I need to start multiple UpdateProduct() at once
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

A BackgroundWorker is a simple way to use a thread.
https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker?view=netframework-4.7.2

Complete example code there to demonstrate.
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

You might also want to look at
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/async

Make certain you really understand multithreading before attempting to use this option.
Avatar of Jesper Christensen

ASKER

Would this work?

public static async Task OperatorAsync()
        {
            var taskList = new List<Task>();
            foreach (var product in products)
            {
                var task = Task.Run(() => upload());
                taskList.Add(task);
            }

            await Task.WhenAll(taskList);

            Console.WriteLine("Upload Successful");
        }
ASKER CERTIFIED SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
C#
C#

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

98K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo