private static void SomeLongJobCancellable(object args) { try { CancellableThreadParams tParams = args as CancellableThreadParams; Console.WriteLine("SomeLongJob started"); for (int i = 0; i < 1000000 && tParams.IsRunning; ++i) { Console.WriteLine($"still working - step {i}"); Thread.Sleep(500); } if (tParams.IsRunning) { Console.WriteLine("SomeLongJob done"); } else { Console.WriteLine("SomeLongJob was cancelled"); } } catch (Exception ex) { Console.WriteLine(ex); } }
private static void AbortingThreadCorrectly() { CancellableThreadParams tParams = new CancellableThreadParams(); Thread tLongJob = new Thread(SomeLongJobCancellable); tLongJob.Start(tParams); Thread.Sleep(1000); tParams.IsRunning = false; }