Windows Forms: Multi Threading in C#
By FoxLearn 7/2/2017 9:13:37 PM 9.91K
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 1: Click 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
Step 2: Design your form as below
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
- How to create a Lucky Draw games in C#
- Windows Forms: Youtube Search with Paging in C#
- Windows Forms: Text to speech in C#
- Windows Forms: Print Picture Box in C#
- Windows Forms: Advanced Filter DataGridView in C#
- Windows Forms: Progress Bar in C#
- Windows Forms: How to Create a Random Password Generator in C#
- Windows Forms: Tag Control in C#
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024