Part 86 Multithreading in C#

23
3



Text version of the video

Slides

All Dot Net and SQL Server Tutorials

All C# Text Articles

All C# Slides

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 and set the following properties.

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.

Nguồn:https://wijstaanvooronzegrondrechten.org/

23 COMMENTS

  1. Why can't i work with multithreading ? above main method [STAThread] is there. this piece of code is preventing another thread to work than the main UI thread. So how can i solve this?
    thanks in advance

  2. Hi Everyone , please help to get the answer of this threading question asked in interview.

    If multiple clients wants to access a log.txt file at a time , how they can do it with treading?

  3. I want to extract denominators of number by pressing "findResult" button and at the same time press another button which i called "count_Button" to start counting in seconds to calculate the length of time needed to get the results but after pressing the first button, the program stops responding and I am not allowed to press the second button,

    What is the problem and how can I get the same result as the video?

    This is the code I wrote

    private void findResult_Click(object sender, EventArgs e)

    {

    for (int i = 1; i <= int.Parse(numberTextBox.Text); i++)

    {

    if (int.Parse(numberTextBox.Text) % i == 0)

    {

    ListBox.Items.Add(i);

    Thread wait = new Thread(stop);

    wait.Start();

    }

    }

    }

    public void stop()

    {

    Thread.Sleep(5000);

    }

    private void count_Button_Click(object sender, EventArgs e)

    {

    beginCounting.Enabled = true;

    beginCounting.Start();

    }

    private void beginCounting_Tick(object sender, EventArgs e)

    {

    if (beginCounting.Enabled == true)

    {

    int count = 0;

    count = count + 1; seconds.Text = count.ToString();

    }

    }

  4. The best tutor I find on youtube Venkat. An awesome explanation with clear voice and mindset. I learned a lot from you.

  5. 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

  6. Thanks for these videos, i would really appreciate if you make series of videos about network programming in C#, keep up the good work.

LEAVE A REPLY

Please enter your comment!
Please enter your name here