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.
source share