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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With