What task is returning and why is the status of the RanToCompletion task

I am new to task-based programming and trying to determine how to return a task and make sure that it was running. The code I received was not what I expected. The console application is as follows:

public static void Main(string[] args)
    {
        var mySimple = new Simple();
        var cts = new CancellationTokenSource();
        var task = mySimple.RunSomethingAsync(cts.Token);
        while (task.Status != TaskStatus.RanToCompletion)
        {
            Console.WriteLine("Starting...");
            Thread.Sleep(100);
        }

        Console.WriteLine("It is started");
        Console.ReadKey();
        cts.Cancel();
    }

public class Simple
{
    public async void RunSomething(CancellationToken token)
    {
        var count = 0;
        while (true)
        {
            if (token.IsCancellationRequested)
            {
                break;
            }
            Console.WriteLine(count++);
            await Task.Delay(TimeSpan.FromMilliseconds(1000), token).ContinueWith(task => { });
        }
    }

    public Task RunSomethingAsync(CancellationToken token)
    {
        return Task.Run(() => this.RunSomething(token));
    }
}

Conclusion:

Starting...
0
It is started
1
2
3
4

Why does the returned task have the status TaskStatus.RanToCompletion compared to TaskStatus.Running, since we see that the while loop is still running? Am I checking the status of a task to include a RunSomething task in a threadpool, and not in a RunSomething task?

+4
source share
2 answers

RunSomething - async void, , - , , , , . Task.Run, RunSomething. , Task.

RunSomething Task, , , , , , ( Task.Run, , ).

+3
+1

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


All Articles