Given is a very common threading scenario:
Declaration
private Thread _thread; private bool _isRunning = false; Start
_thread = new Thread(() => NeverEndingProc()); thread.Start(); Method
private void NeverEndingProc() { while(_isRunning) { do(); } } Possibly used in a asynchronous tcp listener that awaits callbacks until it gets stopped by letting the thread run out (_isRunning = false).
Now I'm wondering: Is it possible to do the same thing with Task? Using a CancellationToken? Or are Tasks only for procedures that are expected to end and report status?
_isRunningneeds to bevolatile. Otherwise, the compiler might realize it's not modified from the current thread and check it only once before the loop starts.