What are Foreground and Background Threads?
Threads are means to parallelize the work being done so that a given task can be accomplished quickly. There exists two broad classification of threads they are called as Foreground and Background Threads. Let us look at them one by one with the help of some examples. Here we will be seeing some examples from the c# context.
Foreground Thread
- These are the threads which are created by default.
- These Threads run until its task gets finished and is not dependent on other threads such as other foreground threads.
- In other words it can be said that an application is kept alive until all its Foreground thread completes its execution and terminates.
- Foreground Threads are mainly used to perform Application critical tasks such as processing the application data which is required to be shown in the User Interface.
- Syntax for creating a Foreground Thread:
Creating a Foreground Thread |
Background Thread
- Background Threads are the threads whose lifetime depends on the Foreground Thread of the application which is running.
- If all the Foreground Thread of an application exits then the application kills all the background threads which are running.
- Background thread is mainly used to perform support operations or book keeping operations such as logging the application activity which are not run in a high priority.
- Syntax for creating a Background thread:
There is a property called IsBackground which determines whether the given thread should run as a Foreground Thread or Background Thread. By default value of this property is false.
Having understood the basics of Foreground and Background Threads lets look at them in Operation:
Scenario 1:
Its because we had one foreground thread which was running when the Main thread exited, therefore background thread can run with the foreground thread to complete its operation.
Scenario 2:
In this case we will have two threads configured as background threads and start them parallelly and observe the output.
Method Handlers for the two Background Threads |
Configuring and starting two background threads |
Output for two background threads |
Comments
Post a Comment