在什么情况下,在方法签名中不使用Task<T>
的情况下,您将返回async
?
我在下面的代码中有这样一种方法,但是在了解发生了什么时遇到了麻烦。
为什么下面的示例代码无法通过任何await
语句执行?
即。为什么Console.WriteLine("4)");
和Console.WriteLine("3)");
和return x;
永远不会执行?
class Program
{
static void Main(string[] args)
{
TestAsync testAsync = new TestAsync();
testAsync.Run();
Console.Read();
}
}
public class TestAsync
{
public async void Run()
{
Task<int> resultTask = GetInt();
Console.WriteLine("2)");
int x = await resultTask;
Console.WriteLine("4)");
}
public async Task<int> GetInt()
{
Task<int> GetIntAfterLongWaitTask = GetIntAfterLongWait();
Console.WriteLine("1)");
int x = await GetIntAfterLongWaitTask;
Console.WriteLine("3)");
return x;
}
public Task<int> GetIntAfterLongWait()
{
Task.Run(() =>
{
for (int i = 0; i < 500000000; i++)
{
if (i % 10000000 == 0)
{
Console.WriteLine(i);
}
}
});
Console.WriteLine("Returning 23");
return new Task<int>(() => 23);
}
}
/*
Output is:
Returning 23
1)
2)
<list of ints>
*/
最佳答案
您的代码中的问题是您实际上是await
从未启动过的任务,因为方法GetIntAfterLongWait
返回了尚未启动的任务的新实例。所以基本上您有一个僵局,等待根本无法开始的事情。
您可以返回Task.FromResult(23)
基本上已经完成的任务,或者您可以实际运行任务Task.Run<int>(() => 23);
关于c# - 声明方法返回类型Task <int>而没有async关键字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54720354/