Why is Task.Wait () not working properly with Console.WriteLine () -.NET Core?

I'm trying to understand the basics of asynchronous programming a little better, so I created the following snippet:

private void TaskContinuations()
{
    // Task for counting prime numbers
    Task<int> primeNumberTask = Task.Run(() =>
        Enumerable.Range(2, 3000000)
        .Count(n =>
            Enumerable.Range(2, (int)Math.Sqrt(n) - 1)
            .All(i => n % i > 0)));

    var awaiter = primeNumberTask.GetAwaiter();

    // primeNumberTask.Wait(); // Option 1: Waiting but not printing (rather unexpected here)

    awaiter.OnCompleted(() => 
    {
        var result = awaiter.GetResult();
        Console.WriteLine(result);
    });

    //primeNumberTask.Wait(); // Option 2: Waiting but not printing (kind of expected here)

    Console.Read(); // Option 3: Works and prints as expected
}

I understand that I need to prevent the main UI task from stopping in order to prevent the background task from completing. Thus, it Console.Read();blocks the user interface thread, and if I do not hit the key before the tasks with a simple number are performed, the output in the console will be correct 216816. Everything is clear so far here.

, , Wait(); ( , OnCompleted) . , ( 1 2) , .

? ( , )

  • / , , , 216816. !

  1. /, , OnCompleted. , .

, - ?

+4
1

, MSDN, OnCompleted,

API , .

-, OnCompleted, , . , - , .Net , awaiter, , - .

ContinueWith task, :

private void TaskContinuations()
{
    // Task for counting prime numbers
    var primeNumberTask = Task.Run(() =>
        Enumerable.Range(2, 3000000)
        .Count(n =>
            Enumerable.Range(2, (int)Math.Sqrt(n) - 1)
            .All(i => n % i > 0)));

    // continuation
    var awaiterTask = primeNumberTask.ContinueWith(t => 
    {
        var result = t.Result;
        Console.WriteLine(result);
    });

    // wait for everything to execute
    awaiterTask.Wait();
}

, ContinueWith . .

+1

Source: https://habr.com/ru/post/1675433/


All Articles