嗨,我正在做一些实验来理解任务。这是我偶然发现的:
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);
}
这将按我的预期工作。立即显示“等待前的结果”,当任务完成后,我们看到“等待后的结果”。但是当我将其更改为使用Task<TResult>
时,执行的优先级似乎发生了变化:
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;
}
“等待前的结果”仅在任务完成时与“等待后的结果”一起显示。看起来整个任务在主线程恢复之前执行,即使 ManagedThreadId 告诉它们在单独的线程上。
有人可以帮我吗?提前致谢!