Multithreading with an Example of .NET Application
page 6 of 9
by Sandeep Acharya
Feedback
Average Rating: 
Views (Total / Last 10 Days): 88195/ 136

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.


View Entire Article

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-2021 ASPAlliance.com  |  Page Processed at 2021-03-02 9:56:24 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search