Background thread vs UI thread - c#

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.

Related

Is there an alternative to use the Background Worker in WPF?

I am a beginner with WPF, in my application I need to perform a series of Initialization steps, these take 10-15 seconds to complete during which my UI becomes unresponsive.
I was using yesterday the background worker but it didn't update my window, in fact it was frozen. Not sure, but maybe it didn't work because this control is only for Windows Forms.
UPDATE:
If not too much trouble, can you post me an example to use the alternative? For my case, the program will get some values from a database in a blucle.
Dispatcher.
The Dispatcher maintains a prioritized queue of work items for a specific thread. This might help you for updating your UI. If you have a lot of UI related initializations even this won't be able to help you much.
Dispatcher is not always an alternative to BackgroundWorker actually. The best practice is to select the more appropriate one as per your requirement. For example if you want something to execute without queuing BackgroundWorker is the solution. On the other hand if queuing is not a problem then Dispatcher is an alternative. For example, Dispatcher is using in Spell checkers and syntax highlighting functionality.
WPF Thread Model
All WPF applications start out with two important threads, one for
rendering and one for managing the user interface. The rendering
thread is a hidden thread that runs in the background, so the only
thread that you ordinarily deal with is the UI thread. WPF requires
that most of its objects be tied to the UI thread. This is known as
thread affinity, meaning you can only use a WPF object on the thread
on which it was created. Using it on other threads will cause a
runtime exception to be thrown. Note that the WPF threading model
interoperates well with Win32®-based APIs. This means that WPF can
host or be hosted by any HWND-based API (Windows Forms, Visual Basic®,
MFC, or even Win32).
The thread affinity is handled by the Dispatcher
class, a prioritized message loop for WPF applications. Typically your
WPF projects have a single Dispatcher object (and therefore a single
UI thread) that all user interface work is channeled through.
NOTE :
The main difference between the Dispatcher and other threading methods
is that the Dispatcher is not actually multi-threaded. The Dispatcher
governs the controls, which need a single thread to function properly;
the BeginInvoke method of the Dispatcher queues events for later
execution (depending on priority etc.), but still on the same thread.
See this thread for more information.
You could also queue items up with the thread pool and run the tasks like that, but be careful, if your tasks need to update the UI when they are finished you will have to marshal the data back to the UI thread.
One could use asynchronous delegates.
http://msdn.microsoft.com/en-us/library/ms228963.aspx
Just make sure if you are doing any UI related updates use:
Dispatcher.CheckAccess()
Here a simple example:
private void HandleUIButtons()
{
if (!btnSplit.Dispatcher.CheckAccess())
{
//if here - we are on a different non-UI thread
btnSplit.Dispatcher.BeginInvoke(new Action(HandleUIButtons));
}
else
{
btnSplit.IsEnabled = true; //this is ultimately run on the UI-thread
}
}
Taken from here:
http://blog.clauskonrad.net/2009/03/wpf-invokerequired-dispatchercheckacces.html

C# - Compact Framework Windows CE - GUI Thread Blocks Higher Priority Threads

I am having an issue where I have a Windows CE compact framework Application written in C#, where I have the primary GUI thread set to normal priority and a communication thread set to above normal priority to get as close to pseudo real time performance. The issue I am having is within a button handler I run a loop to load config data from a file to the GUI before allowing it to be edited. This takes around 2-3 seconds to complete. While this blocking in the event handler is happening, my higher priority communication thread is being blocked. There are no locks are thread syncs in place. The communicatio thread has no dependencies on the GUI thread.
This is how I spawn my comm thread:
MbWorkerThread = new Thread(MbPollingThread);
MbWorkerThread.IsBackground = true;
MbWorkerThread.Priority = ThreadPriority.AboveNormal;
MbWorkerThread.Start();
It is an MTA application. Also, I have tried to use Thread.Sleep(1) in the GUI event handler to yield to the higher priority thread and it does not work. I also tried using signals to yield to the higher priority thread, and that does not work. The only thing that works is if I place Application.DoEvents() in the loop while loading config in the event handler. This of coarse whas just a test, as I do not want to sprinkle Application.DoEvents() throught my code to make it work since I know Application.DoEvents() is dangerous.
My understanding is that the primary GUI thread is a foreground thread, but a thread none the less. Also, I have made the communication thread a background thread just to allow it to be killed when the primary thread is exited.
I have tried everything, I have search the Internet endlessly before asking this question.
Any help will be greatly appreciated.
P.S. - I though about a form timer but I know it runs in the GUI thread so that would not help. I though about another thread but I really did not what to marshall GUI updates via Invoke.
Your program starts in Main(), where you typically call Application.Run( new MyForm() ). Application.Run() implements the standard Windows Message Pump, which deals with messages from the OS and other applications, including user input, inter-process communication, repaint requests, etc.
GUI events, like Button click, are dispatched via this thread. If you perform long-running work in an event handler, other messages are not being processed.
Application.DoEvents() blocks the calling thread, and waits for all pending messages to be processed. If DoEvents helps your communication thread when Sleep(1) did not, then I suspect there is a dependency between your communication thread and the GUI/Message Pump thread.
Even if this is not the case, it is not a good idea to block the GUI thread. Move your file loading into the background with ThreadPool.QueueUserWorkItem() and marshal the results back to the UI at the end with Invoke or BeginInvoke.
BeginInvoke instead of Invoke fixed the issue. Thanks for the replies.

Background threading in c#

I am currently working with threading and backgroundworker in c#. The problem im having is that this. Say i have a main thread for user interaction and a worker thread to process txt files(various editing operations). Then after the backgroundthread runs its contents once, i have a timer start that performs another set of operations. I want these new operations that the timer runs ever x minutes to be run in the same background thread without running the previous txt related operations it ran before the timer started. How can this be done?
You should just use a System.Timers.Timer, which will run its callback on a thread pool thread.
It shouldn't matter which specific thread you run on (as long as it's not the UI thread).
If, for some reason, it does matter (eg, if you're using a single-threaded COM object), you'll need to make a dedicated thread that waits for things to do using a thread-safe queue of delegates.
You want to use an Event Driven method to execute function calls on your worker thread from your UI thread. The way to accomplish this is using BeginInvoke, you can read more about how to use it here: http://www.dreamincode.net/forums/topic/35616-cross-thread-communication-in-c%23/
Add a while loop to the end of your background worker:
while(!stop) { Thread.Sleep(yourIntervalinMilliseconds); ... }
I'd create a stop bool somewhere that the thread looks at when you want it to kick out.

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.

Find the foreground thread from the background thread

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.

Categories