我试图理解有关任务的一些概念,但遇到一些问题作为以下函数。
static void Main(string[] args)
{
int d =newcall();
Console.WriteLine("This is the result after function call");
Console.WriteLine(d);
}
public static int newcall()
{
Task<int> n = new Task<int>(()=> {
Thread.Sleep(10000);
Console.WriteLine("Hello This is the inside the task");
return 3;
});
n.Start();
Console.WriteLine("This is the after task call");
return n.Result;
}
In this case i get the result as:
This is the after task call
Hello This is the inside the task
Hello This is after the result call
3
现在第二种情况是将任务作为返回类型返回而不进行异步(我理解异步返回类型,我试图将任务理解为没有它的返回类型(
static void Main(string[] args)
{ Task<int> d =newcall();
Console.WriteLine("Hello This is after the result call");
Console.WriteLine(d.Result);
}
public static Task<int> newcall()
{
Task<int> n = new Task<int>(()=> {
Thread.Sleep(10000);
Console.WriteLine("Hello This is the inside the task");
return 3;
});
n.Start();
Console.WriteLine("This is the after task call");
return n;
}
In this case result is :
This is the after task call
Hello This is after the result call
Hello This is the inside the task
3
现在在第一种情况下,它看起来像是阻塞了主线程。 但在Sencond案例中,它不会发生。两者之间的唯一区别是,在第二种情况下,我们将返回类型作为 Task,在第一种情况下它是 int。
那么为什么它会给出这样的响应。 返回类型作为没有异步方法的任务的含义是什么?(根据我的理解,我正在两个 case.so 函数内创建新任务,它应该给出相同的响应(。
任何人都可以帮助理解这一点。我已经检查了堆栈溢出,但找到了与异步相关的解决方案。
谢谢
当您使用.Result
时,如果Task
尚未完成,您将阻塞当前线程。观察您对.Result
的两个调用的位置,希望输出结果不是个谜。
请注意,"返回不async
Task
"并没有什么特别之处 -async
在编译时使用,您最终得到的是一个返回Task
的普通旧方法。