Home > database >  C# 10 pocket reference Task example does not work for me
C# 10 pocket reference Task example does not work for me

Time:01-05

The following code example from the C# 10 Pocket Reference does not write the expected result in my console (ubuntu.22.04-x64, dotnet 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#).

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 dotnet run from the project folder. Tried to use dotnet 5.0 but ran into missing GLIBC system dependencies.

CodePudding user response:

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).

It should however be noted, that using TaskAwaiter and OnCompleted is generally not the ideal solution. If possible you should use 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;
}
  • Related