简体   繁体   English

C# 10 pocket reference 任务示例对我不起作用

[英]C# 10 pocket reference Task example does not work for me

The following code example from the C# 10 Pocket Reference does not write the expected result in my console ( ubuntu.22.04-x64 , do.net 6.0.11 ) and I can't tell if I'm missing anything implicit in the book or if the code example is wrong or does not work on all platforms (I am new to C#).来自 C# 10 Pocket Reference 的以下代码示例没有在我的控制台( ubuntu.22.04-x64do.net 6.0.11 )中写入预期结果,我无法判断我是否遗漏了书中隐含的任何内容或如果代码示例错误或不适用于所有平台(我是 C# 新手)。

Task<int> task = ComplexCalculationAsync();
var awaiter = task.GetAwaiter();

awaiter.OnCompleted (() => // Continuation
{
    int result = awaiter.GetResult();
    Console.WriteLine (result); // 116
});

Task<int> ComplexCalculationAsync() => Task.Run ( () => ComplexCalculation() );

int ComplexCalculation()
{
    double x = 2;
    for (int i = 1; i < 100000000; i++)
    x += Math.Sqrt (x) / i;
    return (int)x;
}

I was expecting 116 to be printed to my console when running do.net run from the project folder.当从项目文件夹运行do.net run时,我期待116打印到我的控制台。 Tried to use do.net 5.0 but ran into missing GLIBC system dependencies.尝试使用do.net 5.0但遇到缺少 GLIBC 系统依赖项的情况。

Your program finishes, before the calculation is finished.您的程序在计算完成之前完成。 You never actually wait for the result, you just specify what should happen, when the calculation is done.实际上从不等待结果,您只需指定计算完成时应该发生的事情。 Therefore the program exits, before anything is printed to the console.因此,程序会在任何内容打印到控制台之前退出。

For testing purposes, you can add something to the end of your program, that stops it from exiting.出于测试目的,您可以在程序末尾添加一些内容,以阻止它退出。 You could for example use Console.ReadLine() or Thread.Sleep(10000) .例如,您可以使用Console.ReadLine()Thread.Sleep(10000)

It should however be noted, that using TaskAwaiter and OnCompleted is generally not the ideal solution.但是应该注意,使用TaskAwaiterOnCompleted通常不是理想的解决方案。 If possible you should use await .如果可能,您应该使用await This would also simplify your code:这也将简化您的代码:

int result = await ComplexCalculationAsync();
Console.WriteLine(result);

Task<int> ComplexCalculationAsync() => Task.Run(() => ComplexCalculation());

int ComplexCalculation()
{
    double x = 2;
    for (int i = 1; i < 100000000; i++)
        x += Math.Sqrt(x) / i;
    return (int)x;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM