san*_*ngh 6 c# multithreading task-parallel-library
这可能是一个非常基本的问题,但我只想确保自己能够做到这一点.今天我正在挖掘TPL库,发现有两种方法可以创建Task类的实例.
我一路走来
Task<int> t1 = Task.Factory.StartNew(() =>
{
//Some code
return 100;
});
Run Code Online (Sandbox Code Playgroud)
方式二
TaskCompletionSource<int> task = new TaskCompletionSource<int>();
Task t2 = task.Task;
task.SetResult(100);
Run Code Online (Sandbox Code Playgroud)
现在,我只是想知道这一点
第二个示例没有创建“真正的”任务,即没有执行任何操作的委托。
您主要使用它来向调用者呈现任务界面。看 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);
Run Code Online (Sandbox Code Playgroud)