What are the differences between background and foreground threads?

Asked

Viewed 1,879 times

8

What are the differences between these two types of threads: background and foreground?

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

2 answers

7

The only difference is that the background threads do not determine the life of the execution environment, they do not hold an application running and depend on the foreground threads to continue existing. If all foreground threads close, the Runtime closes independently if it still exists background threads running, evidently closing these as well. And this has some implications on the way this is communicated to the application.

In general threads usually rotate in foreground. That’s the default. Just when you spin one thread which exists according to the others in foreground is that it should be configured as background. Threads Monitors are a good example.

Threads managed by Threadpool sane background for default.

Example demonstrating the functioning.

Think about using a Task in place.

Source: microsoft documentation.

5

Background threads are identical to foreground threads with one exception: a background thread does not keep the managed execution environment running. That is: the difference is that one¹ does not prevent the application from being finished, the other², yes.

¹ Background Thread.

² Foreground Thread.

The correct thing, regardless of the type of thread, is to be careful with your threads, to prevent them from getting out of control and the application getting unexpected results.

Source:

Background threads are identical to foreground threads with one Exception: a background thread does not Keep the Managed Execution Environment running.

http://msdn.microsoft.com/en-us/library/h339syd0(v=vs.110). aspx

  • So, if I have a thread initialized and my program shuts down, it will be executed by the end of your process?

  • If it is Foreground type, the program will run it until the end of Thread. If it is Background it will be stopped and the program will be terminated immediately.

  • @Tony if the background thread is on a critical stretch, the system waits a little longer or is Kill even?

  • [I don’t know how to mark an excerpt as critical, nor do I know for sure it would prevent the thread from ending, but] From analyzing the documentation, which informs that the background thread will be terminated at the end of the application, one should not expect an excerpt, even if marked as critical runs in this hypothetical background thread that is being abruptly terminated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.