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?
RunSomething - async void, , - , , , , . Task.Run, RunSomething. , Task.
RunSomething
async void
Task.Run
Task
RunSomething Task, , , , , , ( Task.Run, , ).
async void (https://msdn.microsoft.com/en-us/magazine/jj991977.aspx) async Task
async -async (, void main), - :
mySimple.RunSomethingAsync(cts.Token).GetAwaiter().GetResult();
.
Source: https://habr.com/ru/post/1663153/More articles:How to ask user to change default applications - androidChoosing between overloading primitive types or using a reference to a Number object - javahttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1663150/how-to-feed-multiple-files-to-a-background-process-using-makefile&usg=ALkJrhjJUEipJvGSDdqFweZLNR-pyqZcQACrap Wrap Function in Java Callable - javaquery with similar offer in scalikejdbc - scalikejdbcMicro Service vs Nano Service? - web-servicesΠ‘ Π½Π΅ΡΠΊΠΎΠ»ΡΠΊΠΈΠΌΠΈ Spring WebMvcConfigurerAdapter, ΠΊΠ°ΠΊ Ρ ΠΌΠΎΠ³Ρ ΠΊΠΎΠ½ΡΡΠΎΠ»ΠΈΡΠΎΠ²Π°ΡΡ ΠΏΠΎΡΡΠ΄ΠΎΠΊ ΠΊΠ»Π°ΡΡΠΎΠ² ΠΊΠΎΠ½ΡΠΈΠ³ΡΡΠ°ΡΠΈΠΈ? - spring-mvcWhen reassigning a hyper key / cap is blocked by F18 using Hammerspoon, can it be used with modifiers - hammerspoonCSS Does the background image stretch horizontally and repeat vertically? - cssSearch for date difference - rAll Articles