Windows Forms: Multi Threading in C#

How to use Multithreading in C#. This example demonstrates how to create and start a thread in Windows Forms

The advantage of threading is the ability to create applications that use more than one thread of execution. For example, a process can have a user interface thread that manages interactions with the user and worker threads that perform other tasks while the user interface thread waits for user input.

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "MultiThread" and then click OK

c# multi threadStep 2: Design your form as below

multi thread in c#

Step 3: Add code to button click event handler as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        private void btnThread1_Click(object sender, EventArgs e)
        {
            //Start new thread
            Thread thread = new Thread(t =>
              {
                  for(int i = 0; i < 100; i++)
                  {
                      int width = rd.Next(0, this.Width);
                      int height = rd.Next(50, this.Height);
                      this.CreateGraphics().DrawEllipse(new Pen(Brushes.Red, 1), new Rectangle(width, height, 10, 10));
                      //Delay
                      Thread.Sleep(100);
                  }
              })
            { IsBackground = true };
            thread.Start();
        }

        Random rd;

        private void Form1_Load(object sender, EventArgs e)
        {
            rd = new Random();
        }

        private void btnThread2_Click(object sender, EventArgs e)
        {
            //Start new thread
            Thread thread = new Thread(t =>
            {
                for (int i = 0; i < 100; i++)
                {
                    int width = rd.Next(0, this.Width);
                    int height = rd.Next(50, this.Height);
                    this.CreateGraphics().DrawEllipse(new Pen(Brushes.Blue, 1), new Rectangle(width, height, 10, 10));
                    //Delay
                    Thread.Sleep(100);
                }
            })
            { IsBackground = true };
            thread.Start();
        }
    }
}

VIDEO TUTORIALS