问题
Hi I'm making some experiment to understand Tasks. Here what I stumbled upon:
static void Main(string[] args)
{
Console.WriteLine(String.Format("Master in the thread {0}", Thread.CurrentThread.ManagedThreadId));
Task t1 = Task.Factory.StartNew(TaskDoNothing);
Console.WriteLine(String.Format("Result before wait"));
Task.WaitAll(t1);
Console.WriteLine(String.Format("Result after wait"));
Console.ReadLine();
}
static void TaskDoNothing()
{
Console.WriteLine(String.Format("Task in the thread {0}", Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(3000);
}
This will work as I expected. The "Result before wait is shown right away and when the task is done, we see the "Result after wait". But when i change it to use Task<TResult>
, the priority of execution seems changed:
static void Main(string[] args)
{
Console.WriteLine(String.Format("Master in the thread {0}", Thread.CurrentThread.ManagedThreadId));
Task<int> t1 = Task<int>.Factory.StartNew(TaskDoNothing);
Console.WriteLine(String.Format("Result before wait: {0}", t1.Result));
Task.WaitAll(t1);
Console.WriteLine(String.Format("Result after wait: {0}", t1.Result));
Console.ReadLine();
}
static int TaskDoNothing()
{
Console.WriteLine(String.Format("3- Task in the thread {0}", Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(3000);
return 3;
}
The "Result before wait is only shown when the task is done along with the "Result after wait". It looks like the whole Task is executed before the main thread resumes even if the ManagedThreadId tells that they are on separate thread.
Can someone help me with that? Thanks in advance!
回答1:
Task.Result
is a blocking operation. In fact, you wait for the task to finish. If you want the result but not wait, then you can use ContinueWith
回答2:
From my own experience, Task.Result
waits until it have the result of the operation.
来源:https://stackoverflow.com/questions/16488818/whats-the-difference-between-using-task-and-tasktresult-in-c-sharp