First of all, let's make your tick asyncronous, to not block the current thread:
public class TickMe { private int _counter; private object locker = new object(); public async Task Run(CancellationToken cancelationToken) { _counter = 0; while (!cancelationToken.IsCancellationRequested) { await Task.Delay(200); Console.WriteLine("tik" + _counter); lock (locker) { _counter++; } } } }
- Note the use of CancellationToken to stop the execution.
- Note the use of lock to deal with the counter.
Then we create a CancellationToken to stop the execution of your asyncronous method, and pass it as parameter for the function on the main method and it's ready to go
public class Program { public static async Task Main(string[] args) { CancellationTokenSource source = new CancellationTokenSource(); var cancelationToken = source.Token; var tick = new TickMe(); Task.Run(async () => await tick.Run(cancelationToken)); await Task.Delay(1000); await Task.Delay(1000); Console.WriteLine("foo"); await Task.Delay(1000); source.Cancel(); await Task.Delay(1000); await Task.Delay(1000); Console.WriteLine("bar"); } }
The results should be closer to this:
tik0 tik1 tik2 tik3 tik4 tik5 tik6 tik7 tik8 foo tik9 tik10 tik11 tik12 tik13 bar
Run()method currently blocks the thread. Convert it to anasyncmethod, replace` Thread.Sleep()` withawait Task.Delay()and learn how to use a CancellationToken that you'd pass to theRun()method and cancel it using the client.CancellationToken. The alternatively, when you yank the rug out from under the library when it has no idea that could happen can lead to... tricky to diagnose issues later. The library could be doing practically anything, including stuff that it only intends to temporarily change and you stop it being able to revert those changesTickMe.Runat all? If not theres basically nothing you can do to stop it running. Also yourClient.Runmethod has a local variableinstancewhich is completely separate from your class-level variable making it inaccessible outside that method (But im guessing this is a typo)