Reputation: 832
Simplifying, I have WPF application that has two class: a main window class with GUI and a worker class, which operates on a file. In main window, when user clicks a button, the worker thread starts.
I would like to make a button in main window, which stops worker. However not killing a thread, but notifying it, that user has aborted a thread and allow it to close writer and save file.
I was looking on stackoverflow for a long, but all questions are not about my problem. I would like to point out that I'm not iterating through a loop etc, therefore I cannot use a flag. I would like to raise an event from my main window on a thread class. How can I do that?
Upvotes: 1
Views: 1176
Reputation: 4893
Create a CancellationTokenSource in your main window class. Send the CancellationToken to the worker thread. Code the worker to observe the token. MSDN has reference the cancellation patterns, review it there.
Whenever cancellation is needed, initiate it from UI thread by calling CancellationTokenSource.Cancel()
You don't have to loop, you can observe if process is cancelled by waiting on WaitHanndle of the token: CancellationToken.WaitHandle.WaitOne()
WaitOne will wait indefinitely until Cancel is called.
Upvotes: 3
Reputation: 1728
Use CancellationTokenSource
https://msdn.microsoft.com/ru-ru/library/system.threading.cancellationtokensource%28v=vs.110%29.aspx
Just call its method Cancel()
on button click.
Upvotes: 1