Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Wait() necessary after using Task.Factory.StartNew()?

Almost all documentation that I have seen on using the C# 4.0 Task.Factory.StartNew states that in order to wait for the Task to complete, you need a Wait. But my initial testing shows that it is unnecessary. Can anyone else give me confirmation on this? I'm curious as to why so much online and printed references say you should call Wait.

Here's a simple console app that shows that I don't need the Wait statement, so I commented it out. Whether or not I comment out the tsk.Wait(), the output is the same.

Expected output in all cases is as follows:

Main thread starting.
After running MyTask. The result is True
After running SumIt. The result is 1
Main thread ending.

The code:

class Program
{
    // A trivial method that returns a result and takes no arguments.
    static bool MyTask()
    {
        Thread.Sleep(2000);
        return true;
    }

    // This method returns the summation of a positive integer
    // which is passed to it.
    static int SumIt(object v)
    {
        int x = (int)v;
        int sum = 0;
        for (; x > 0; x--)
            sum += x;
        return sum;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Main thread starting.");
        // Construct the first task.
        Task<bool> tsk = Task<bool>.Factory.StartNew(() => MyTask());
        // I found this Wait statement to be completely unnecessary.
        //tsk.Wait();
        Console.WriteLine("After running MyTask. The result is " +
        tsk.Result);
        // Construct the second task.
        Task<int> tsk2 = Task<int>.Factory.StartNew(() => SumIt(1));
        Console.WriteLine("After running SumIt. The result is " +
        tsk2.Result);
        tsk.Dispose();
        tsk2.Dispose();
        Console.WriteLine("Main thread ending.");
        Console.ReadLine();
    }
}
like image 219
Tam Bui Avatar asked Jan 12 '11 19:01

Tam Bui


People also ask

When should I use task factory StartNew?

Factory. StartNew in async code: You need a task that represents only the first (synchronous) part of an asynchronous method, instead of a task representing the entire method. You need to specify a custom TaskScheduler , instead of using the thread pool scheduler.

What does task factory StartNew do?

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.

What is the difference between task run () and TaskFactory StartNew () methods?

Task. Run(action) internally uses the default TaskScheduler , which means it always offloads a task to the thread pool. StartNew(action) , on the other hand, uses the scheduler of the current thread which may not use thread pool at all!


1 Answers

If you just want to wait for the task to finish, the recommended course of action is to call .Wait(). For a Task (as opposed to a Task<T>) this is the only option.

For a Task<T>, however, there is also .Result, which also waits, and that is what you are using. So in your case it is unnecessary to call .Wait().

like image 114
Timwi Avatar answered Nov 09 '22 23:11

Timwi