Home > database >  create async method that calulate the sum and limit numbers of threads
create async method that calulate the sum and limit numbers of threads

Time:03-04

I'm trying to create a async method in my c# application and want to make it with limited threads the method should calculate the sum of many arrays each array in separate threads, but if we have more than 4 like 6 arrays, first you run 4 threads and once a thread is released you need to run one more and so on.

this is my code :

static int CalculateRouter(Route route)
        {
            int total = route.sum(route.routers);
            return total;
        }

Async method that calculates best route asynchronously by calculating total time required for each route in a separate thread.

 public async Task <int> AsyncBestRoute(List<Route> Routes)
        {
            var tasks = new List<Task<int>>();
            foreach (var route in Routes)
            {
                tasks.Add(Task.Run(() => CalculateRouter(route)));
            }
            int[] results = await Task.WhenAll(tasks);
            int minValue = results.Min();
            Console.WriteLine(minValue);
            Console.WriteLine("********************");

            return await Task.FromResult(minValue);
        }

is my work are correct in the method ? and how i can but limits of threads ? it's my first time to work within it and don't know how i should delay with it, there's any help or idea ?

CodePudding user response:

I'm trying to create a async method in my c# application and want to make it with limited threads the method should calculate the sum of many arrays each array in separate threads, but if we have more than 4 like 6 arrays, first you run 4 threads and once a thread is released you need to run one more and so on.

First: asynchrony is quite different than parallelism, although they're both forms of concurrency. The whole point of asynchrony is to use fewer threads, and parallelism is to use more threads.

Since you're dealing with a CPU-bound operation (summing values), you want parallelism, not asynchrony. Parallel and PLINQ are the appropriate tools here. Generally, PLINQ is a bit cleaner if you have a result (or sequence of results). Both Parallel and PLINQ support limiting the number of threads.

public int BestRoute(List<Route> Routes)
{
  return Routes.AsParallel()
      .WithDegreeOfParallelism(4)
      .Select(CalculateRouter)
      .Min();
}

If you also need asynchrony, e.g., if you need to free up the UI thread, then you can use await and Task.Run as such:

// Run BestRoute on a thread pool thread to avoid blocking the UI
var minValue = await Task.Run(() => BestRoute(routes));
  • Related