Use case for foreground and background threads - c#

In C# Threading, by default the new thread is a foreground thread.
But what is the use case of a background thread?
Also, on what does the main thread run -> on foreground or background thread?

According to MSDN, the main difference between foreground and background threads is:
Background threads are identical to foreground threads with one
exception: a background thread does not keep the managed execution
environment running. Once all foreground threads have been stopped in
a managed process (where the .exe file is a managed assembly), the
system stops all background threads and shuts down.
So, the use case for background threads are, tasks that should not prevent your process from terminating.
If you use a thread to monitor an activity, such as a socket
connection, set its IsBackground property to true so that the thread
does not prevent your process from terminating.
Considering the difference, UI thread should be foreground so that it keeps the process running until UI shuts down. If it was a background thread, the process stopped running as soon as no other foreground thread was running.
Edit:
Since you can signal the foreground threads when process is supposed to terminate, I don't see any special use case that cannot be implemented using foreground threads only. Since those thread may need to be informed about termination to free resources or perform an action, manually signaling them (rather than relying on the fact that they will be terminated because there are background) could be a better choice. But making them background would be a "Just in case" thing, that if for some reason they doesn't get signaled, they do not prevent process from terminating.

Related

is Thread.Join() a good way to let main thread update GUI while a thread func is working

I have Main() function which displays in label the current time. There is a button which calls a function LoadUserImage() for reading image files and writing them to database and then showing the result of reading and writing in another label. While LoadUserImage() is running I want the Main() function to still display in label the current time. My instructor tells me to put LoadUserImage() in a separate thread and then join it. But on his lectures he tells that Thread.Join() makes the main thread kind of pause temporarily The question is: if joining makes the main thread pause then how can it update the GUI in my case?
The purpose of Thread.Join() is to make sure that the background thread started previously is stopped properly, but it is not needed for the background thread to work.
In your case, you start the long-running operation in a background thread, and in the main thread proceed with the other activities. You need to call Thread.Join() only at the end, when the main thread has already finished its activity. If at that point the background thread had terminated already, Thread.Join() will return right away, while if the background thread is still busy, it will block (in the main thread) until the background thread has finished. This is the way to make sure an app is not exiting until operations are active in the background.
I suppose in your Main() (running in the main thread) you have some loop which periodically updates some UI. This loop has some exit condition (e.g. by reacting to pressing Enter in a Console.ReadLine(), or a Ctrl-C handler). Once the loop is exited, it can call Thread.Join().
If proper exit is not implemented at all in your sample program (which is not so nice, but usual in such sample program), then you don't have to call Thread.Join() at all! When the process exits, all threads disappear anyways.

Are background workers stopped when process that created them finishes

I have a Windows Service that when it gets started It creates many backgroundworkers. and each backgroundworker monitors its own Queue in memory with the pending items to process.
When the process that created the backgroundworkers --windows service-- is stopped (either by request or because it crashed) are these background workers stoped or left orphan and still running ?
Do I need to write the code stop the backgropund workers when the windows service is about to be stopped ?
BackgroundWorkers use threads with IsBackground set to true, which means it will terminate when all non-background threads have terminated.
If your BackgroundWorker is going to do something where it should not be shut-down until it is completed, then it should set Thread.CurrentThread.IsBackground = false before it begins that crucial part, and set it back to true upon completion.
Edit: It's worth adding, that a process shutdown (unhandled exception, process killed through the task-manager or replacement, etc.) will end all threads. It's rather the reverse; ending all non-background threads will end the process (and take all background threads with them). It's this you need to worry about in terms of reacting to user input requesting the process terminate (service stop, last visible window closed, etc.)
In .NET applications and services when the main thread terminates all child background threads terminate as well.

Does Application.Exit() kill background threads?

I created a form which runs multiple background threads. I added another class which handles exceptions and errors if any. When the code runs, if an error occurs that should force the application to close can I just use Application.Exit()? Will that kill the background threads as well?
No, it will not. Application.Exit() will simply force the windows message pump to post a Quit message, which will terminate your application's main thread. However, the process itself will continue to run until the background threads complete.
Update: as commenters have correctly pointed out, if your thread's IsBackground property is set to True, terminating the main thread via Application.Exit() will shut down the process.
No. Thread termination is cooperative.

Application process not ending when I close the form? (C#)

Experimenting with the TcpClient and TcpListener class and for some reason when I have a couple of threads running and I close the form the process does not end but the form disappears.
I have to manually kill the process with the VS IDE or task manager.
Nothing in the form is still running from what I can tell when I close the program but the process does not end.. I insert breakpoints everywhere and even the console output says the threads exited.
Anyone know what's going on here?
The main thread of your application is waiting for the threads your spawned to finish. You can set the IsBackground property of your threads to true so they do not stop your process from terminating:
From MSDN:
A thread is either a background thread or a foreground thread.
Background threads are identical to foreground threads, except that
background threads do not prevent a process from terminating. Once all
foreground threads belonging to a process have terminated, the common
language runtime ends the process. Any remaining background threads
are stopped and do not complete.

Reason why my application would not exit?

We have an application written in .net, c#, winforms. We noticed that sometimes when closing the application, the process remains.
I'm not sure how I can reproduce that behavior, so I'm looking for some clues as to why the application wouldn't exit.
The application uses a bit of background threads. Thread pools. Wondering if that could be the cause. Anything else could have this effect?
If you have thread's that have IsBackground property set to false that are alive after application is closed, they will remain
The application uses a bit of
background threads. Thread pools.
Wondering if that could be the cause.
Anything else could have this effect?
It most definitely could be the cause though I cannot be certain that it actually is. One way to test this hypothesis to make sure all threads that have been explicitly created are designated as background threads. This can be done by setting Thread.IsBackground = true which will allow the application to terminate if the main thread ends. If there is at least one thread for which IsBackground = false then the CLR keeps the host process running.
Its likely to be a thread left running. If you have a look at the process in task manager you can see when a thread starts, and how many are left running when it exits by adding the 'Threads' column from the view menu.
I would start by making sure you start and end on the same thread count.
Get Process Explorer and possibly Process Monitor and see what thread is left suspended or running.
If you are able to run in debug and you close the form, VS should not return to the normal code edit mode (it will still have the pause and stop buttons from debug active). You can then press Pause and check the Threads window to see where the call stacks are stuck for threads that are still active.

Categories

Resources