0

After reading multiple articles issued at different years I got more confused then before.

I wanted to know how to make sure the tasks I create will run on multiple cores ??

The function below has to handle lots of files being uploaded to the server :

private void FileSystemWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {

        var SyncTask = new Task(() => 
        {

            //DO A LOT OF WORK HERE
        });

        SyncTask.Start();

    }

I just couldn't find a straight answer if this is the way to go on 4.7.2 .NET framework or not ?

  • 3
    The recommended way is to use `Task.Run`. See also the [Task constructor documentation](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.-ctor?view=netcore-3.1#System_Threading_Tasks_Task__ctor_System_Action_) which states that using the constructor is only for advanced scenarios when you need to separate Task setup and kick-off, which is extremely rare. Also you should await your task. – ckuri Apr 25 '20 at 15:29
  • Tasks will run on thread pool, it manages how to run the task and which thread to use – Pavel Anikhouski Apr 25 '20 at 15:32
  • Ok sure, buy will the thread pool assign the tasks to run on multiple cores if needed ? – Tom Boudniatski Apr 25 '20 at 15:35
  • Usually using `Task.Run()` you may not care about cores. But you may set LongRunning option to force new Thread creation. And there's an option to consider of using `async`/`await`. It's the way to do the job with saving thread resources. And yes, it may use multiple cores. For the way to go: go to the .NET Core 3.1. – aepot Apr 25 '20 at 16:25
  • Thanks , I tested Task.Run() with windows recourse monitor and I could clearly see that the work load was spread among all cores equally by using Task.Run() – Tom Boudniatski Apr 26 '20 at 05:32

1 Answers1

0

The task itself will run on a single core. If you want "//DO A LOT OF WORK HERE" to run on multiple cores, you need to parallelize that work either by spawning tasks from this task (see also Child tasks, or by using the simpler Parallel.

Otherwise, whether you use your approach or just Task.Run(..) it doesn't quite matter in your case.

EDIT See this article, it explains nicely the difference.

Nick
  • 4,787
  • 2
  • 18
  • 24