santosh singh
santosh singh

Reputation: 28692

Instance of Task class (Task.Factory.StartNew or TaskCompletionSource)

This is probably a pretty basic question, but just something that I wanted to make sure I had right in my head. Today I was digging with TPL library and found that there are two way of creating instance of Task class.

Way I

 Task<int> t1 = Task.Factory.StartNew(() =>
                {
                    //Some code
                    return 100;

                });

Way II

  TaskCompletionSource<int> task = new TaskCompletionSource<int>();
  Task t2 = task.Task;
  task.SetResult(100);

Now,I just wanted to know that

  1. Is there any difference between these instances?
  2. If yes then what?

Upvotes: 6

Views: 2645

Answers (2)

tugberk
tugberk

Reputation: 58494

As you are not firing any async operation in Way 1 above, you are wasting time by consuming another thread from the threadpool (possibly, if you don't change the default TaskScheduler).

However, in the Way 2, you are generating a completed task and you do it in the same thread that you are one. TCS can been also seen as a threadless task (probably the wrong description but used by several devs).

Upvotes: 1

adrianm
adrianm

Reputation: 14736

The second example does not create a "real" task, i.e. there is no delegate that does anything.

You use it mostly to present a Task interface to the caller. Look at the example on msdn

    TaskCompletionSource<int> tcs1 = new TaskCompletionSource<int>();
    Task<int> t1 = tcs1.Task;

    // Start a background task that will complete tcs1.Task
    Task.Factory.StartNew(() =>
    {
        Thread.Sleep(1000);
        tcs1.SetResult(15);
    });

    // The attempt to get the result of t1 blocks the current thread until the completion source gets signaled.
    // It should be a wait of ~1000 ms.
    Stopwatch sw = Stopwatch.StartNew();
    int result = t1.Result;
    sw.Stop();

    Console.WriteLine("(ElapsedTime={0}): t1.Result={1} (expected 15) ", sw.ElapsedMilliseconds, result);

Upvotes: 4

Related Questions