AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1028&pId=-1
Multithreading with an Example of .NET Application
page
by Sandeep Acharya
Feedback
Average Rating: 
Views (Total / Last 10 Days): 65682/ 77

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.


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-24 9:06:51 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search