C# child thread is still working even main thread exit - c#

I happened to read Semaphore class sample as below from msdn:
https://msdn.microsoft.com/en-us/library/system.threading.semaphore%28v=vs.110%29.aspx
It's a console app, however something confused me that child threads are able to work even main thread exits.
From my understanding, when main thread/process exits, all child threads will be terminated, that's why usually we signal and wait child threads to finish before main thread stops.
Am I wrong or the behaviour has been changed in .net due to reference?

If you want the child thread to abort on the termination of the parent thread, it must be set as a Background thread.
t.IsBackground = true;
t.Start(i);
Otherwise, all foreground threads run to completion before the process exits

Related

Does the task still survive when the main thread that creates it has been killed in c#?

I have a main thread that creates a task using:
new TaskFactory(cancellationToken).StartNew(() => DoSomething(cancellationToken),
TaskCreationOptions.LongRunning);
I wonder if the task still survive when the main thread that creates the task has been killed in c#.
If a process' main thread is terminated, the process aborts. When a process is killed, all threads (and other owned resources) are closed/terminated/killed also.
Therefore, if your process' main thread created a worker thread and the main thread is killed, the worker thread is also terminated.
Don't be confused by the TaskCreationOptions.LongRunning enum - this is just an indicator to the underlying thread-pool manager that it might want to create this thread outside the normal constraints on maximum thread-pool size.
If AppDomain (usually equal to process) survives "killing" of the thread that created the task then task will continue to exist.
What happens when task try to finish depends on synchronization context - if it had to continue on aborted thread it will throw/hang, if it can continue on thread pool thread than task will be able to finish.
Note that usually for UI based apps aborting main thread means at least stopping event loop which will result in process to be considered "unresponsive" and possibly killed.

Cross Thread Exception When Closing Application

I am sometimes getting a cross thread exception when closing my application which uses two threads (main thread and secondary). I think what is happening is that the main UI thread is being disposed while the secondary one is still running, and since the secondary one sometimes invokes things on the UI thread it is crashing.
Do I need to manually close the secondary thread in the FormClosing event?
Thanks for the info.
Do I need to manually close the secondary thread?
No and yes.
No, if your secondary thread is a background thread. You can inspect/set the IsBackground property on your secondary thread. All background threads are are automatically stopped by CLR when there is no foreground thread running anymore. All ThreadPool threads, for example, are background threads.
Yes, however, is when you perform some critical task in your secondary thread and you don't want it to be abruptly stopped. In that case, you will have to implement appropriate logic to stop your secondary thread.
Once you have a long-running dedicated thread, you have to implement shutdown logic for it. Reason is simple: the app is not killed by OS until at least one thread alive. And yes, there is no such thing as "main thread", all threads are equal from OS perspective.
Given that, once your app plans to exit, you must
Signal to the second thread that termination expected
Wait for the second thread until it exits from his thread proc
Now you're free to exit.
The recommended approach in multi-threaded windows application is using Method Invocation instead of directly manipulating controls which were created on another thread. This way you never get Cross Thread Exception. For example you can set a textbox's text like this:
form1.BeginInvoke(new MethodInvoker(()=>textbox1.text = "Hello!"));
For more information see:
http://msdn.microsoft.com/en-us/library/ms171728(v=vs.85).aspx

Control.Invoke() stucks

I know there are several threads concerning this topic, but I think mine is different.
In my application I open a form where the user can input some parameters for a upcomming printing. This printing is supposed to be run in a background worker. So I fire that background worker with the event "OnFormClosing".
Within that background worker I need to access the GUI and change/read it, so I need a control.Invoke(). "Sometimes" the Invoke keeps stuck at the invoke call itself and doesn't execute the delegate. My main thread is working fine and is not blocked. I still can interact with the GUI doing other stuff. Before posting any code: Are there any other conditions for executing a control.Invoke() other than
The main GUI thread is not blocked
The contorl must exist, the handle created and not be disposed
The main thread doesn't need to be free and exactly the invoke is called correct? It should continue once the main thread is idle...
Thanks for any help
Update:
Here is the thread situation during that issue:
The Main thread is executing this:
Application.Run(appContext);
So it is idle.
The worker thread is waiting at this line:
fileName = (string)cbPrintFile.Invoke(new Func<String>(() => cbPrintFile.Text));
which is not executed like I state above. cbPrintFile is a combobox
Invoke is "enqueue and wait for it to be processed". If it is becoming "stuck", that suggests that you have deadlocked, for example because the UI thread is still in an event-handler waiting on the worker. If the code is properly de-coupled, you can probably replace the Invoke with BeginInvoke, which allows the worker to continue after queuing the work. Of course, it would also be good to ensure that the UI is never waiting on a worker. This can be done accidentally if trying to hold a lock (on the same object) in both places. You can investigate simply by pausing the application, pressing ctrl+d,t to bring up the threads, and ctrl+d,c to see the call-stack of each in turn.

Is a process killed if the thread that started it is aborted?

If I create a thread that starts a process and later abort that thread, does the process stop executing as a result of the thread being aborted ?
I am not clear as to what the question is asking. When you start a process by launching an .exe file, there will be the primary thread for the process; if this thread aborts for whatever reason then the process will also halt.
If you are talking about a thread launching another process (via the Process class Start method for example) then the exiting of the thread that launched the process will not stop the process.
No, since the thread will be in a totally different process (you just started a new process), there is no link between them.
(also if you started another thread, the other thread would not be killed).

Wait for all worker threads to end [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# Threading/Lock confusion
I've got following problem: I have monitoring class, which is running it's own thread that writes from queue into file (so the main application doesn't have to wait on IO). But, when main application thread ends (control flow runs after it's last line), the monitor thread ends too, even if it is still running (full queue).
Is there any way, without modifying main thread to wait till the worker thread is done? C#.
EDIT: I cannot modify main thread. I'm writing only 'support' code for huge application with given API (one static method containing what shall I write, where is read from configuration), there is no way how to change threads, main app must not depend on my code.
Switch them around. Make your main thread the one that monitors, and spawn the worker threads (write from Q to file) from there.
Or have the main thread startup threads for monitor and work, and then have the main thread spin and wait (loop until it gets abort/complete notifications from the other threads)
You can use a ManualResetEvent and call WaitOne() at the end of your main execution thread. When the worker thread is done simply signal the ManualResetEvent and it will continue execution of the main thread.

Categories

Resources