Find the foreground thread from the background thread - c#

When you are in the context of the background thread.
Thread.IsBackground == true
There is a way to find the foreground thread calling this background thread ?
Thanks for your help
Update: The thread created are background and handled by a threadpool (Inside the Workflow Foundation Runtime). I have no way to add the reference from the main thread inside each background thread. There is no way to find that foreground thread from the threadpool ?

There's no such relationship. Any thread can create a new thread, including another background thread. After the new thread has been created, there's no relationship between the creating thread and the new thread. If you need to know which thread created the new thread, you'll need to pass that information in the ThreadStart.
EDIT: For thread-pool threads, by the time any of your code is running I assume it's been specified by you as a task somewhere, in some way. If you need some information to be available (whether that's a thread ID or anything else) you need to put it in the context for that task.

Related

In c#, how to check the thread from threadpool is a worker thread or an I/O thread?

Is it possible to recognize a thread is a worker or an I/O.
I know the code
Thread.CurrentThread.IsThreadPoolThread
this code is to show whether it is a thread pool thread, but it seems no method to show if it's a worker thread.
How can I check it? Is it possible?
There is no difference between the threads except for the pool they were/are in as you can read here: Simple description of worker and I/O threads in .NET
A thread has no knowledge about the pool that it came from. So this is not possible.

What happens when a Dispatcher created on a background thread is not shutdown? How to make sure that a dispatcher is properly shut down?

The following is one of the remarks on Dispatcher class.
If you create a Dispatcher on a background thread, be sure to shut down the dispatcher before exiting the thread.
What are the consequences if one fails to invoke shut down on a dispatcher created on a background thread?
I have an MFC application which creates a WPF window on a background thread. Consequently, a dispatcher is created. When I close the WPF window first, I get to explicitly invoke shutdown on the dispatcher, but when I close the MFC application, the WPF window closes along.
It seems the dispatcher is being shut down implicitly, or the thread is being aborted. Which is it?
Update:
The following method creates a new thread and opens the wpf window.
public void ShowWindow(SomeObject someObject)
{
System.Threading.Thread thread = new System.Threading.Thread((tuple) =>
{
Tuple<Dispatcher, SomeObject> data = tuple as Tuple<Dispatcher, SomeObject>;
Window window = new WPFWindow(data.Item1, data.Item2);
System.Windows.Threading.Dispatcher.Run();
this.tmp = 0;
});
thread.SetApartmentState(System.Threading.ApartmentState.STA);
thread.IsBackground = true;
thread.Start(new Tuple<Dispatcher, SomeObject>(Dispatcher.CurrentDispatcher, someObject));
}
So, I put a break along the statement "this.tmp = 0;" and it doesn't get hit when I close the MFC application. Is it safe to assume that the Dispatcher is not being shutdown, but the thread is being aborted?
If the thread is aborted, what are the consequences?
Update:
On another project, I ran into a problem where the GC doesn't seem to be doing its job. It turns out, it's related to a Dispatcher started on a background thread that is not being shutdown. The WPF application's memory usage just kept increasing every time a task is ran on background thread. So, be sure to invoke shutdown on Dispatchers created on a background thread whether you created a Dispatcher object explicitly or not.
Not invoking shutdown on Dispatcher created on background thread will cause memory/resource leak. Dispatcher objects hang onto resources. Hence, the GC aren't able to clean them up.
To make sure that a dispatcher is shut down properly, in my case, I have to spawn the background thread from the MFC side of the application then have the main thread wait on it before it completely shuts down. As Hans Passant pointed out, MFC doesn't wait unless it is explicitly told.
If you don't shutdown dispatcher, thread will stuck in message loop and don't exit
In the main thread you can do something like
Dispatcher.FromThread(thread).InvokeShutDown();
However this will cause the 'Dispatcher.Run()' to generate an exception, so you also need to change it to
try
{
System.Windows.Threading.Dispatcher.Run();
}
catch {}

Background thread vs UI thread

Could any one help me to figure out background thread and UI thread in C#.I have googled it but i coudnt find article illustrate both.
A UI thread creates UI elements and waits and responds to events like mouse clicks and key presses. You can only access the UI elements from the UI thread.
There are two types of threads: background and foreground. A UI thread is an example of a foreground thread.
The difference between background and foreground threads is pretty simple. Background threads don't stop a process from terminating, but foreground threads do. When the last foreground thread stops, then all the background threads are also stopped and the process ends.
This website has a lot of information about threading as well as parallel programming: http://www.albahari.com/threading/
Good luck
There is another key issue to keep in mind. There is a single U.I. thread and you can only call methods on U.I. objects in that thread. In another thread you need to call Control.Invoke() to flip to the U.I. thread if you are doing something like update a status bar.

In CLR, what is difference between a background and foreground thread?

What is difference between a background and foreground thread ?
See this page:
Foreground threads have the ability to prevent the current application from terminating. The CLR will not shut down an application (which is to say, unload the hosting AppDomain) until all foreground threads have ended.
Background threads (sometimes called daemon threads) are viewed by the CLR as expendable paths of execution that can be ignored at any point in time (even if they are currently laboring over some unit of work). Thus, if all foreground threads have terminated, any and all background threads are automatically killed when the application domain unloads.
From MSDN:
Background threads are identical to
foreground threads with one exception:
a background thread does not keep the
managed execution environment running.
By default, threads are foreground threads, meaning they keep the application alive for as long as
any one of them is running. C# also supports background threads, which don’t keep the
application alive on their own – terminating immediately once all foreground threads have ended.
There are two types of threads -
Foreground Thread
Background Thread
Whenever we open any application, then the main UI thread is of type Foreground thread. This is the default thread type. Suppose when we create any new thread. By default, the thread current type is foreground itself. If you want to change the type of the thread you will have to execute threadName.IsBackground = true;.
Now the main story starts. What is the difference? And why do we need these two types?
Foreground Thread: Suppose we are creating a thread ThreadA. If we need the thread ThreadA to keep executing in spite of all other threads are aborted, even if our main UI thread is no more alive, then in this case we must keep our thread type Foreground. So if you keep your thread foreground type, then even if you close your application, the foreground thread ThreadA will keep running. You can track it also in your task manager.
Background Threads: Now if you change your thread type to be background thread, then this thread is going to be dependent on other foreground threads. Because In the case if none of the thread of type foreground is running anymore, then all the background thread will have to be forcefully aborted.
The important difference between background and foreground threads that is not mentioned yet is the following: a background thread executes only when the number of foreground threads executing is smaller than the number of processors MSDN.
Background thread is going to be killed no matter if it's not finished yet when there will be no active foreground threads.
An example of foreground thread is Application Main thread.
Background thread examples are:
System.Threading.Task class
System.Threading.ThreadPool class
For more information, check out out this MSDN article.
If any of the foreground or background threads terminate, the application dies immediately. It is possible to change the thread from foreground to background and vice versa at any time during application lifetime. CLR creates two kinds of threads to better support AppDomain. CLR will forcibly end any background threads that are running if the foreground thread terminates. Any threads created by native code that enter the managed execution environment are marked as background threads.

how to make User Controls to run on their own thread

how can i make a user control to run on its own thread ?
e.g. by following code in a user control , coz user control uses main app thread it make main thread to sleep
Thread.Sleep(TimeSpan.FromMinutes(2));
User controls need to run on the UI thread because that is a restriction in the Windows API. If you try and use Windows Forms controls from another thread you will get an exception.
You can run other code in another thread, but use the UI thread to update the controls. You can use BackgroundWorker for this. Or you can use the InvokeRequired and Invoke or BeginInvoke methods on the control instance to have it execute code on the UI thread.
You mention you want to use a mutex lock. A mutex is to avoid having multiple threads access a resource at the same time. If all your code is running in the same thread then you don't need a lock at all.
Objects don't really "run" themselves - methods are executed on a thread.
Now if you want a particular method to execute in a different thread, you need to either create a new thread, use the threadpool explicitly, or use something which uses the threadpool for you - such as BackgroundWorker.
What are you doing when you want to sleep for two minutes? Could you avoid sleeping by just setting a timer to fire (in the UI thread) in two minutes instead? If this is part of some long-running process, you should use BackgroundWorker or some other way of executing on a different thread, but with the control itself still handling updates and events on the UI thread.

Categories