Task class instance (Task.Factory.StartNew or TaskCompletionSource)

This is probably a pretty simple question, but I just wanted to make sure everything was in my head. Today I was digging the TPL library and found that there are two ways to create an instance of the Task class.

Method I

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

Method II

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

Now I just wanted to know that

  • Is there any difference between these instances?
  • If so, then what?
+6
source share
2 answers

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

You use it mainly to represent the Task interface to the caller. See an 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); 
+4
source

Since you are not starting any asynchronous operation in Way 1 above, you are wasting time consuming another thread from threadpool (possibly if you do not change the default value of TaskScheduler ).

However, on path 2, you create a completed task, and you do it in the same thread as you. TCS can also be thought of as a threadless task (perhaps a misnomer, but used by several developers).

0
source

Source: https://habr.com/ru/post/885968/


All Articles