首先,贴代码
class Program
{
static void Main()
{
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);
Console.WriteLine("第一个Factory" + Thread.CurrentThread.ManagedThreadId);
});
// 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;
Console.WriteLine("主1:"+Thread.CurrentThread.ManagedThreadId);
sw.Stop();
Console.WriteLine("(ElapsedTime={0}): t1.Result={1} (expected 15) ", sw.ElapsedMilliseconds, result);
// ------------------------------------------------------------------
// Alternatively, an exception can be manually set on a TaskCompletionSource.Task
TaskCompletionSource<int> tcs2 = new TaskCompletionSource<int>();
Task<int> t2 = tcs2.Task;
// Start a background Task that will complete tcs2.Task with an exception
Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
tcs2.SetException(new InvalidOperationException("SIMULATED EXCEPTION"));
Console.WriteLine("第二个Factory" + Thread.CurrentThread.ManagedThreadId);
});
// The attempt to get the result of t2 blocks the current thread until the completion source gets signaled with either a result or an exception.
// In either case it should be a wait of ~1000 ms.
sw = Stopwatch.StartNew();
try
{
result = t2.Result;
Console.WriteLine("t2.Result succeeded. THIS WAS NOT EXPECTED.");
}
catch (AggregateException e)
{
Console.WriteLine("AggregateException:" + Thread.CurrentThread.ManagedThreadId);
Console.Write("(ElapsedTime={0}): ", sw.ElapsedMilliseconds);
Console.WriteLine("The following exceptions have been thrown by t2.Result: (THIS WAS EXPECTED)");
for (int j = 0; j < e.InnerExceptions.Count; j++)
{
Console.WriteLine("\n-------------------------------------------------\n{0}", e.InnerExceptions[j].ToString());
}
}
Console.WriteLine("主2:" + Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();
}
}
1,int result = t1.Result;//要等待 t1.Result的结果值
2,tcs1.SetResult(15);//tcs1.SetResult(15);设置t1.Result的结果值
3,tcs1.SetResult(15);执行后才会执行int result = t1.Result;。否则就会一直停在int result = t1.Result;
4,可以看出是不同线程间返回的值