bob mason
bob mason

Reputation: 915

Can't fully utilize my CPU when using async Task in C#

I can't get my CPU to 100% using Async method in C#, my average is around 50%. I am unsure if there is a lock, garbage collection, or other behind-the-scene tasks that are slowing my App. The task and its results are pure calculations, there are no I/O or network requests. Does my code need any enhancements?

enter image description here

            for (int i = 0; i < loops; i++)
            {
                List<Task<List<Distance>>> DistanceTask = new List<Task<List<Distance>>>();
                foreach (var item in dstpart)
                {
                    List<string> itemKeywords = item.Keywords.Split(',').Take(10).ToList();
                    DistanceTask.Add(Task.Run(() => CalculateDistances(itemKeywords))); 
                    //one task takes around 5sec to complete, no IO or network requests
                }
                var results = await Task.WhenAll(DistanceTask);
                foreach (var r in results)
                {
                    //evaluate the results, no IO or network operations here, It's few (ms)
                }
            }

Upvotes: 0

Views: 457

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89361

There's nothing wrong with the pattern. This simplification pegs all my CPUs

var loops = 100;
var dstpart = Enumerable.Range(1, 100).ToList();
for (int i = 0; i < loops; i++)
{
    List<Task> tasks = new List<Task>();
    foreach (var item in dstpart)
    {
        
        tasks.Add(Task.Run(() =>Spin() ));
        //one task takes around 5sec to complete, no IO or network requests
    }
    await Task.WhenAll(tasks);
  
}

void Spin()
{
    var sw = new Stopwatch();

    sw.Start();
    while (sw.ElapsedMilliseconds < 5000)
        Thread.SpinWait(10000);
}

Upvotes: 1

Related Questions