Multithreading with an Example of .NET Application
 
Published: 11 Oct 2006
Abstract
In this article Sandeep discusses the basics of multithreading and how it could be effective over a single thread application. It also includes the advantages and disadvantages of multithreading. The article includes the complete .NET project for creating a simple multithreaded application.
by Sandeep Acharya
Feedback
Average Rating: 
Views (Total / Last 10 Days): 65679/ 87

Introduction

Threads are also known as lightweight processes.  However, if we go into depth then we would know that a thread is not actually a process; rather it provides ways for executing different parts of a program.  Now let us discuss what it actually means by multithreading.  Multithreading (as the name suggests multi+threading) is nothing but an efficient execution of multiple threads at a time to enhance the performance of the application.  For example, we are doing a file copy operation with a status bar on UI indicating the completion percentage.  Here we need to keep track of how much file size is copied and at the same time we also need to advance the progress bar accordingly.  This can not be done efficiently in a single thread and you have to use multiple threads.

The above example shows just one instance where we are forced to use multithreading.  However, when we are not forced we can also use this for the betterment of the application performance. And of course, all this depends on how effectively the thread is implemented in an application.  Most of the developers do not use multithreaded applications and continue with a single thread.  However, the efficient use of threads can give birth to a highly powerful application.

Requirements

Visual Studio .NET 2003

Multithreading

Whenever an application runs, it runs under a main thread.  However, running a single thread can sometimes lead to unnecessary performance and locking issues.  So if the application can be broken into multiple threads without hampering the flow of the main thread, then using it is always better.

Figure 1

The following care needs to be taken while going for multithreading.

While using the threads we need to be very careful about the flow of each individual thread. Otherwise, there is a heavy probability of deadlock creation when multithreading comes into picture.

All the sub-internal threads need to be ended before the main thread ends.

Benefits of Multithreaded Applications

The image given below shows the difference between the single threaded and multi-threaded applications.  In a single threaded application, the flow gets confined to one thread only.  Therefore, one independent portion of the application may also have to wait for a long time to get executed, resulting in an overall increase of Response and execution time.  In a multithreading environment the independent section of an application gets executed by the separate threads and can continue execution by also doing time-span overlaps.  So at any particular instant there is every possibility of execution of more than one thread, resulting in a significant rise in performance.

Figure 2

Threading Priorities

As discussed above, Deadlock is a major issue that usually comes up while multithreading.  To avoid this up to a certain extent and also manage the flow of sub-threads, each thread gets associated with a priority.

When a thread starts its priority it can either be set by the programmer or by the operating system. In a locking situation the highest priority thread usually locks the system by keeping the resources engaged, while other low priority threads keep waiting for it. This creates a locking situation.

Basics of Threads in .NET

In .NET, the threading is handled through the System.Threading namespace.

Creating a variable of the System.Threading.Thread type allows you to create a new thread to start working with.

It is clear to everybody that the concept of threading is to go off and do another task.  The Thread constructor requires the address of the procedure that will do the work for the thread.

The AddressOf is the parameter that the constructor needs to begin using the thread.

Below is an example of a simple threading application.

Listing 1

Imports System.Threading
Public Class Form1
  Inherits System.Windows.Forms.Form
 
  Dim th1 As Thread
  Dim th2 As Thread
 
  Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
    th1 = New Thread(AddressOf proc1)
    th2 = New Thread(AddressOf proc2)
 
    th1.Start()
    th2.Start()
  End Sub
 
  Sub proc1()
    Dim iCount As Integer
    For iCount = 1 To 10
      cmb1.Items.Add(iCount)
    Next
  End Sub
  Sub proc2()
    Dim iCount As Integer
    For iCount = 11 To 20
      cmb2.Items.Add(iCount)
    Next
  End Sub
End Class

The output of the above code is shown in Figures 3 and 4.  The complete source code for our sample application can be downloaded from the Downloads section given at the end of this article. The given code populates two dropdowns on a form.  Now let us see a comparison between the single threaded application and the multithreaded application.

In the given scenario, if we implement the single thread [demon thread], then we need to populate the 1st dropdown for which we need to run a loop.  After the 1st loop is over then go for the second loop.

Figure 3

Figure 4

Here, in a multithreaded application, in order to populate the 2nd dropdown, we do not need to wait for the population of the 1st one.  That means at the same time we can populate the two dropdowns; this bring the execution time to half of the execution time of 1st one.

The above example is a simple one that demonstrates how the multithreaded application can bring the execution time to (1/n)th of the total execution time, where n = Number of threads used.

Some questions with answers

Q1.     What is the minimum number of threads that used to run in any .Net application?

A:       There should be at least two threads running in a .net application.  They are the main thread and the GC (Garbage collector).

Q2.     What is Suspend and Resume in threading?

A:       Suspend allows you to block a thread until another thread calls Thread.Resume.

Q3.     Differentiate between Thread.Sleep and Thread.Suspend?

A:       The difference among these two is the later does not put the process in a waiting state immediately.  The process gets suspended if the .net runtime determines that it is a safe place to suspend the process.

Q4.     What is Daemon Thread?

A:       Daemon threads run in the background.  An example is a Garbage Collector (It runs until the .NET code runs or otherwise it becomes idle).

Q5.     While executing Thread1, if we call Thread2..Join(), what will happen?

A:       Here Thread1 will wait until Thread2 completes the execution and then invokes Thread1 again.

Downloads

Conclusion

The multithreading is something that can be either a wish or a curse (dual role).  It all depends on how efficiently the developer uses this in his application.  My guess is that by now you understand how this can play the dual role.  So please be cautious while going for this fellow so that you can keep developing powerful applications.



User Comments

Title: Improve Basic Multithreading Code   
Name: Abhijeet Rana
Date: 2012-05-11 2:08:03 AM
Comment:
Hi All,
If you copy and pest above code as usual in .Net the you will get error saying "Cross-thread operation not valid: Control 'cmb1' accessed from a thread other than the thread it was created on." as i did that so i got this error
Error occurred because main thread is running for form and listbox control is not accessible at this point
So i have modified this code as below-

Imports System.Threading

Public Class Form1
Inherits System.Windows.Forms.Form

Dim th1 As Thread
Dim th2 As Thread

'Declaring Delegate here
Private Delegate Sub proc1Delegate
Private Delegate Sub proc2Delegate

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
th1 = New Thread(AddressOf proc1)
th2 = New Thread(AddressOf proc2)

th1.Start()
th2.Start()
End Sub

Sub proc1()
'Calling Dalegate here and passing addressof Proc1
Dim DelProc1 As proc1Delegate(AddressOf proc1)
Dim iCount As Integer

If cmb1.InVokeRequired Then
cmb1.InVoke(DelProc2)
Else
For iCount = 1 To 10
cmb1.Items.Add(iCount)
Next
End If

End Sub

Sub proc2()
'Calling Dalegate here and passing addressof Proc2
Dim DelProc2 As proc2Delegate(AddressOf proc2)
Dim iCount As Integer

If cmb2.InVokeRequired Then
cmb2.InVoke(DelProc2)
Else
For iCount = 11 To 20
cmb2.Items.Add(iCount)
Next
End If

End Sub
End Class


* Correct me if i wrong
Title: eagle   
Name: desert eagle
Date: 2011-10-25 7:18:46 AM
Comment:
desert eagle want to know how to work through multiThreading
Title: Good   
Name: Farogh Ahmed
Date: 2011-05-31 10:38:57 AM
Comment:
Very good explanation with example.

Thanks,
Title: it is nice article for beginner   
Name: Anjanareddy
Date: 2010-11-18 6:15:24 AM
Comment:
It is very useful for beginner.i tried ur program but when i give breakepoint that time it work perfectly.is it need brake point while debugging ?
nice article.Thank You
Title: How to overcome- "Cross Thread Operation" problem   
Name: Balakrishnan.S
Date: 2010-07-23 2:33:58 PM
Comment:
When running the downloaded appliation Showing error "Cross-thread operation not valid: Control 'cmb1' accessed from a thread other than the thread it was created on."

Please give me the solution......
Title: article is really good   
Name: neha
Date: 2010-07-17 1:56:12 AM
Comment:
information regarding multithread concept is very good n easy to understand. Its very helpful for the beginners
Title: ss   
Name: ss
Date: 2010-07-08 8:19:37 AM
Comment:
When running the downloaded appliation Showing error "Cross-thread operation not valid: Control 'cmb1' accessed from a thread other than the thread it was created on."
Title: Thank you   
Name: Bilal
Date: 2010-05-16 3:40:40 AM
Comment:
many thanks
Title: multitreading   
Name: Amin Rasmin
Date: 2010-03-30 9:25:29 PM
Comment:
thank u for ur information, it's help me, i'l try to use it.
Title: It doesn't work   
Name: Anonymous
Date: 2010-03-19 5:34:30 AM
Comment:
This article is good and easy to understand, but the code just doesn't work for me. I have created a C# web app and filling listboxes. Below is my code.

protected void Page_Load(object sender, EventArgs e)
{
Thread th1;
Thread th2;

th1 = new Thread(Proc1);
th2 = new Thread(Proc2);

th2.Start();
th1.Start();

}
private void Proc1()
{
for (int i = 1; i <= 10; i++)
{
ListBox1.Items.Add(i.ToString());
//Thread.Sleep(100);
}
}
private void Proc2()
{
for (int i = 11; i <= 20; i++)
{
ListBox2.Items.Add(i.ToString());
//Thread.Sleep(10);
}
}

Some times it works and only populates the ListBox 2 as I have called thread 2 on top of thread 1. If I call thread 1 before thread 2 it will populate only List Box 1.

Even with the Thread.Sleep uncommented the code wont work.

Can anyone please tell me what is wrong with this piece of code as I am totally clueless.
Title: example of multithreading in microsoft word   
Name: mariyan
Date: 2009-10-08 5:38:37 AM
Comment:
can you give some example of multi-threading in microsoft word
. because i not yet to understand about it process when microsoft office word is runing
Title: I have this same problem like Eman mentioned here   
Name: kumar
Date: 2009-07-02 1:16:00 PM
Comment:
I dont see second combo populating until I debug the code step by step using break points. Am I doing something wrong plz clarify?
Title: Best Article to Start with   
Name: Geetha
Date: 2009-05-28 3:45:53 AM
Comment:
Hi Sandeep,

The article is really nic to understand basic of mutithreading.
Its useful for beginners.
Title: nice   
Name: Dima
Date: 2009-04-12 9:07:59 PM
Comment:
very nice ............
Title: Nice Article   
Name: Jignesh Patel
Date: 2008-08-19 9:54:41 PM
Comment:
Very nice ..easy to understand for beginners..
Thanks..
Title: RE: It won't work   
Name: Ibrahim mohsen
Date: 2008-05-22 9:48:07 AM
Comment:
you shouldn't access any controls inside threads

you may make flag and in the end of thread method raise this flag and make timer to check if this flag is raised.

if it is raised access what you need of controls
Title: It won't work   
Name: Abhishek
Date: 2008-04-28 3:58:57 PM
Comment:
Cross-thread operation not valid: Control 'comboBox2' accessed from a thread other than the thread it was created on.

I'm getting this error. I'm not able to do the multi-threading in any way on windows systems. Anybody have any working sample/example?
Title: Shallow Coverage   
Name: ApuDeb
Date: 2008-04-26 2:17:48 AM
Comment:
Hello Sandeep, I found the coverage of the topic shallow and found a lot of room to improve it.
Title: kill a thread that is spawned by another process   
Name: Mia
Date: 2008-01-24 3:44:06 PM
Comment:
I have an app that starts a thread. The threads opens a new aspx page and runs a process to fill the page with data.
The currentThread in the new aspx page is the currentThreadID of the app and not the threadID of the new thread. How can I kill the new thread from the new aspx page. if I just kill the currentThread, it will shut down the whole app.
Title: Very Simple   
Name: Abdulla Hussein
Date: 2007-09-28 5:58:50 PM
Comment:
Very Simple Articals , and it is help me to understanding MultiThreading in a nice way . Thanks :)
Title: Multithread   
Name: Rajesh
Date: 2007-04-04 2:18:12 AM
Comment:
Nice article
Title: need help   
Name: Dhananjay k
Date: 2007-03-21 8:32:20 AM
Comment:
hi,i am trying to make online multiplayer game(card game like poker)now in current state the game is almost completed and in LAN it working fine. but whn i try to use online database(ie fm remote db server) the game sleeps can anyone suggest me hw can i solve the prob. ( using vb.net and sql server 2000)
Title: possibility   
Name: balaji
Date: 2007-03-16 7:22:59 AM
Comment:
i want to move multiple objects and , iwant to see at run time those actions in asp.net 2005 version
Title: answers to questions   
Name: KraGiE
Date: 2007-02-13 6:44:19 AM
Comment:
First off, this is a pretty good beginners look at multithreading in .net. Would be nice to see more low level info, and practical do's for threading.

1) annie xavier
if you're only using one thread, it would probably be better not to sleep it. However, it all depends on the scenario itself. Can you use a timer and/or an event callback that will trigger your working thread to start?

2) Eman
Typical problem with debugging multithreaded applications. Get used to utilizing thread names, and conditional breakpoints. you can also use windbg if you've learned how already.
Title: Doubt   
Name: annie xavier
Date: 2007-02-07 4:52:49 AM
Comment:
i am not using threads in my application. Now in my application i need to wait for soemtime even before i execute a piece of code. Is it ok if i specify thread.sleep in the main thread itself?
Title: there is a proplem   
Name: Eman
Date: 2007-01-28 5:39:24 AM
Comment:
i have a proplem that wehen i run a project motr than once thread dosen't work unless i debug it line by line by using
breakpoint
why????????????????????
please give me answer by mail orin this page quickly
thanks
Title: Hi   
Name: Padmapolisetti
Date: 2007-01-11 4:35:46 AM
Comment:
Hello,
Ur material helped me a lot in learning about the threads.
can u provide some more material on threads in depth.
Title: hello   
Name: hassan hayek
Date: 2006-11-04 2:27:32 PM
Comment:
thanks
Title: jj   
Name: ashish
Date: 2006-10-23 11:14:19 PM
Comment:
ur material is very good n m very satisfied n got new things from ur sites everything is worhty for me

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 5:33:47 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search