我有这个“简单”测试代码...(不要打扰类方法的奇怪使用...)
我正在努力抓住Task<>
错综复杂...我想我有点了解Task<>.Start()
/Task<>.Result
模式(也许因为它更像“旧”Thread.Start()
?)但是一旦我觉得抓住了一些东西(所以我就扔进去await
关键字)...然后所有的东西再次纠缠在一起:-(
为什么我的代码在第一个任务完成后立即返回?为什么它不等待Task.WhenAll()
?
static BigInteger Factorial(BigInteger factor)
{
BigInteger factorial = 1;
for (BigInteger i = 1; i <= factor; i++)
{
factorial *= i;
}
return factorial;
}
private class ChancesToWin
{
private int _n, _r;
public ChancesToWin(int n, int r)
{
_n = n;
_r = r;
}
private Task<BigInteger> CalculateFactAsync(int value)
{
return Task.Factory.StartNew<BigInteger>(() => Factorial(value));
}
public async Task<BigInteger> getFactN()
{
BigInteger result = await CalculateFactAsync(_n);
return result;
}
public async Task<BigInteger> getFactN_R()
{
BigInteger result = await CalculateFactAsync(_n - _r);
return result;
}
public async Task<BigInteger> getFactR()
{
BigInteger result = await CalculateFactAsync(_r);
return result;
}
}
private async static void TaskBasedChancesToWin_UseClass()
{
int n = 69000;
int r = 600;
List<Task<BigInteger>> tasks = new List<Task<BigInteger>>();
ChancesToWin ctw = new ChancesToWin(n, r);
tasks.Add(ctw.getFactN());
tasks.Add(ctw.getFactN_R());
tasks.Add(ctw.getFactR());
// The getFactR() returns first of the other two tasks... and the code exit!
BigInteger[] results = await Task.WhenAll(tasks);
// I don't get here !!!!
BigInteger chances = results[0] / results[1] * results[2];
//Debug.WriteLine(chances);
}
static void Main(string[] args)
{
TaskBasedChancesToWin_UseClass();
}
异步方法同步运行,直到第一次等待,此时它们将控制权返回给调用方法,通常返回一个代表异步操作其余部分的任务。TaskBasedChancesToWin_UseClass
不返回任务,因此调用者无法等待它完成。这就是为什么你不应该使用async void
在事件处理程序之外。
Since Main
在操作有机会完成之前,不会等待您的应用程序结束。
你通常会等待await
但自从你Main
不能是可以同步阻止的异步方法Wait
关于从返回的任务TaskBasedChancesToWin_UseClass
:
async static Task TaskBasedChancesToWin_UseClass()
{
// ...
}
static void Main()
{
TaskBasedChancesToWin_UseClass().Wait();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)