How to end a thread gracefully at the moment when the calling process is completed or killed?

So, I'm thinking of an instance of the class where I want the thread to execute for the life of the class, but end when the process calling the class no longer works. This does not apply to the parent thread ending the child, but the only rotation (possibly in the waiting queue) is the thread exiting gracefully without holding resources, etc.

I think in C ++ you can say that the thread terminates with the volatile bool from the destructor, however in C # ~ it is not a destructor, it is a finalizer. I could not successfully complete the thread using the finalizer. Maybe I'm missing something there. I know that it is better to practice that all threads die a natural death, without signaling its termination, but it is simply inefficient to spawn a thread every time I need to do something. Yes, I know about thread pools, but I think it would be better if one listener thread answered class calls and died skillfully when the class is placed in gc.

The real trick, I think, I can know, or how I know when the class that starts the thread is first placed in gc. Is IDisposable what I'm looking for? I do not use unmanaged code here.

+4
source share
1 answer

I think you basically have two reasonable choices.

Selection:

If you really do not have unmanaged resources, you can simply close the system when the program closes. This is obviously the easiest solution.

You can only worry if you use objects that have methods that should be called. This includes open files, but probably won't include something like a font.

If you do this, you must ensure that the thread starts as a "background" thread. The only difference between the background thread and the foreground thread is that when the program closes, all background threads will be automatically terminated, but the foreground threads will not.

If you use Task , by default it will be launched as a background thread.

You definitely will not want to do this if your thread will do IO on disk or do anything else that should not be interrupted.

Second choice:

Add a mechanism for canceling the stream using the CancellationTokenSource and organize its use when the program is turned off and wait for the stream to exit.

In this case, you don’t care whether the stream will be priority or background, because you yourself will control the shutdown of the program, and the stream will be stopped properly before the program exits.

If you take this route, you can encapsulate the stream cancellation logic and other methods of processing the flows in a class that wraps the stream. You can then add the Dispose() method so that you can create a class inside the using block to ensure that it is turned off correctly even before exceptions.

I used this approach quite often, and it seems to work very well.

+5
source

Source: https://habr.com/ru/post/1486103/


All Articles