As msdn says:
Waits for the Task to complete execution.
in addition, there is the following statement:
Wait
blocks the calling thread until the task completes.
So myTask.Wait();
looks redundant as method CallExpensiveStoredProc
returns nothing.
As a good practise, it would be better to use async
and await
operators when you deal with asyncronous operations such as database operations.
UPDATE:
What we have is:
We run LongRunning
, so new Thread is created. It can be seen in source files.
Then we call myTask.Wait();
. This method just waits when myTask
will finish its work. So all jobList
iterations will be executed sequantially, not parallely. So now we need to decide how our job should be executed - sequantially(case A) or parallelly(case B).
Case A: Sequantial execution of our jobs
If your jobs should be executed sequntially, then a few questions might be arisen:
- what for do we use multithreading, if our code is executing sequantially? Our code should be clean and simple. So we can avoid using multithreading in this case
- when we create a new thread, we are adding additional overheads to the threadpool. Because thread pool tries to determine the optimal number of threads and it creates at least one thread per core. That means when all of the thread pool threads are busy, the task might wait (in extreme cases infinitely long), until it actually starts executing.
To sum up, so there is no gain in this case to create new Thread
, especially new thread using LongRunning
enum.
Case B: Parallel execution of our jobs
If our goal is to run all jobs parallely, then myTask.Wait();
should be eliminated because it makes code to be executed sequntially.
Code to test:
var jobs = new List<int>(){1, 2, 3 };
jobs.ForEach(j =>
{
var myTask = Task.Factory.StartNew(() =>
{
Console.WriteLine($"This is a current number of executing task: { j }");
Thread.Sleep(5000); // Imitation of long-running operation
Console.WriteLine($"Executed: { j }");
}, TaskCreationOptions.LongRunning);
myTask.Wait();
});
Console.WriteLine($"All jobs are executed");
To conclude in this case B, there is no gain to create new Thread, especially new thread using LongRunning
enum. Because this is an expensive operation in the time it takes to be created and in memory consumption.