Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 710
santosh singh Avatar asked Apr 15 '11 09:04

santosh singh


1 Answers

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);
like image 68
adrianm Avatar answered Sep 28 '22 00:09

adrianm