Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 86 - Multithreading in C#

Suggested Videos 
Part 83 - Generic stack collection class
Part 84 - Real time example of queue collection class in c#
Part 85 - Real time example of stack collection class in c#



In this video we will discuss
1. What is a process and a thread
2. Simple multithreading example



Before we discuss multithreading, first let's understand the following terms 
1. Process - Process is what the operating system uses to facilitate the execution of a program by providing the resources required. Each process has a unique process Id associated with it. You can view the process within which a program is being executed using windows task manager.
2. Thread - Thread is a light weight process. A process has at least one thread which is commonly called as main thread which actually executes the application code. A single process can have multiple threads.

Please Note: All the threading related classes are present in System.Threading namespace.

Multithreading Example: Create a new windows forms application with 2 buttons and a listbox control as shown in the image below, and set the following properties.
Multithreading Example

For the first button control, set
Name = btnTimeConsumingWork
Text = Do Time Consuming Work

For the second button control, set
Name = btnPrintNumbers
Text = Print Numbers

Double click on each of the buttons to generate their respective click event handlers.

For the listbox control, set 
Name = listBoxNumbers

Copy and paste the following code in Form1.cs file
using System;
using System.Threading;
using System.Windows.Forms;

namespace ThreadingExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnTimeConsumingWork_Click(object sender, EventArgs e)
        {
            btnTimeConsumingWork.Enabled = false;
            btnPrintNumbers.Enabled = false;

            DoTimeConsumingWork();

            btnTimeConsumingWork.Enabled = true;
            btnPrintNumbers.Enabled = true;
        }

        private void DoTimeConsumingWork()
        {
            // Make the thread sleep, to introduce artifical latency
            Thread.Sleep(5000);
        }

        private void btnPrintNumbers_Click(object sender, EventArgs e)
        {
            for (int i = 1; i <= 10; i++)
            {
                listBoxNumbers.Items.Add(i);
            }
        }
    }
}

1. At this point if we run the program, one thread is automatically created. This thread is called as the Main thread or UI thread. This is the thread that is responsible for doing all the work. 
2. Now when you click "Do Time Consuming Work", the first 2 lines of code to disable the button is executed. As a result both the buttons are disabled. 
3. DoTimeConsumingWork() method is called next, and at this point the application is unresponsive as it is waiting for the method to complete. Note that the buttons are still disabled and you cannot click on any of them.
4. Finally, once the DoTimeConsumingWork() method completes the buttons are enabled and the application is responsive.

Now change the code in btnTimeConsumingWork_Click() event handler method as shown below.
private void btnTimeConsumingWork_Click(object sender, EventArgs e)
{
    btnTimeConsumingWork.Enabled = false;
    btnPrintNumbers.Enabled = false;

    // Create another THREAD to offload the work of
    // executing the time consuming method to it.
    // As a result the UI thread, is free to execute the
    // rest of the code and our application is more responsive.
    Thread backGroundThread = new Thread(DoTimeConsumingWork);
    backGroundThread.Start();
    //DoTimeConsumingWork();

    btnTimeConsumingWork.Enabled = true;
    btnPrintNumbers.Enabled = true;
}

So one of the benefits of multithreaded programming is that it makes your application more responsive. In our next video, we will discuss the rest of the advantages and disadvantages of multithreaded programming.

6 comments:

  1. HI Venkat Sir.. If possible please share some tutorials on tasks (TPL)

    ReplyDelete
  2. Hi, Venkat Sir, If it is please share some tutorial on SSRS

    ReplyDelete
  3. Hi, Venkat sir If possible please share some tutorial on window form connectivity..

    ReplyDelete
  4. Thanks Venkat. Earlier it was very dififcult concept for me.

    ReplyDelete
  5. If i copy code and paste code into the my visual studio 2010 i am not getting numbers in to the listbox.

    ReplyDelete
  6. Hello SIr
    I need some help
    i want to clear the memory after form closed the form is open in the MID parent form
    how to Dispose and Clear the allocated memory
    thanks in Advance

    ReplyDelete

It would be great if you can help share these free resources