Can I safely rely on IsBackground in threads when the application terminates?

I am running some background threads in a GUI. Currently, I am implementing a personal theme cancellation code, but there is an IsBackground property in streams, and according to MSDN they cancel themselves.

I know that it will be Thread.Abort (), which is unpleasant, but nothing happens in this background thread, I need to maintain the correct state or require the correct cleanup.

I try to avoid any crashes if the user simply closes the application in the middle of the background thread. Since multi-threaded scripts are quite difficult to verify, I would like to get your opinion on this.

Basically, instead of rolling my own code, should I just set IsBackground = True and forget about the rest?

+5
source share
4 answers

Thread.Abort throws an exception, so if your code is already correctly written to use finally / using, it should fail gracefully and free up all resources.

change

I should probably give a little more detail. First, the exception is of type ThreadAbortException. The interesting thing is that even if you catch him and do nothing, he will not disappear. In other words, as soon as it leaves your catch block, it still throws. This is so that the (usually bad) practice of catching Exceptions and swallowing does not stop the flow from interrupted. If you really want to stop the interrupt, you need to catch the exception and then call Thread.ResetAbort.

+4

MSDN IsBackground:

. , . , , , . .

, , , , , .. , , , .

+5

IsBackground:

IsBackground , (UI) . , .

, ?

, .NET - , - ​​ . ( , Thread.Abort , , , .)

, ok , ?

If this is not the case, then probably it should be the flow of the foreground. Therefore, a thread working with file descriptors or open database connections should ideally be in the foreground when the application finishes working on terminating this thread before exiting it.

+5
source

I think it depends on the resource. For example, a socket closes safely when the process terminates. For some resource, you better free it before exiting the stream.

0
source

All Articles