Multiple Task.Run() & WaitAll()

Scenario:

From MSDN:

For I/O-bound code, you await an operation that returns a Task or Task<T> inside of an async method.
For CPU-bound code, you await an operation that is started on a background thread with the Task.Run method.

You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.

Solution:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
        protected  void ProcessItems(Item[] item)
        {
            var tasks = item.Select(i =>
                Task.Run(() =>
                {
                    var stopwatch = Stopwatch.StartNew();
                    ProcessItemsAsync(d).Wait();
                    stopwatch.Stop();
                        }));
            Task.WaitAll(tasks.ToArray());
        }

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...