简体   繁体   中英

Notify thread to stop - raise event in another thread and class - C#

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?

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.

使用CancellationTokenSource https://msdn.microsoft.com/ru-ru/library/system.threading.cancellationtokensource%28v=vs.110%29.aspx只需在单击按钮时调用其方法Cancel()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM