Skip to content

Instantly share code, notes, and snippets.

@heiswayi
Created April 14, 2016 07:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heiswayi/adc8176e043f7ff399205d01a8e2c549 to your computer and use it in GitHub Desktop.
Save heiswayi/adc8176e043f7ff399205d01a8e2c549 to your computer and use it in GitHub Desktop.
C# multithreading
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Example1
{
class Program
{
static void Main(string[] args)
{
ThreadStart testThread1Start = new ThreadStart(new Program().testThread1);
ThreadStart testThread2Start = new ThreadStart(new Program().testThread2);
ThreadStart testThread3Start = new ThreadStart(new Program().testThread3);
Thread[] testThread = new Thread[3];
testThread[0] = new Thread(testThread1Start);
testThread[1] = new Thread(testThread2Start);
testThread[2] = new Thread(testThread3Start);
foreach (Thread myThread in testThread)
{
myThread.Start();
//myThread.Join(); // wait specific thread to complete first, remove if async
}
int count = 0;
while (count++ < 10)
{
Console.WriteLine("Thread 0 (Main) Executed " + count + " times");
Thread.Sleep(1);
}
Console.ReadLine();
}
public void testThread1()
{
//executing in thread
int count = 0;
while (count++ < 10)
{
Console.WriteLine("Thread 1 Executed " + count + " times");
Thread.Sleep(1);
}
}
public void testThread2()
{
//executing in thread
int count = 0;
while (count++ < 10)
{
Console.WriteLine("Thread 2 Executed " + count + " times");
Thread.Sleep(1);
}
}
public void testThread3()
{
//executing in thread
int count = 0;
while (count++ < 10)
{
Console.WriteLine("Thread 3 Executed " + count + " times");
Thread.Sleep(1);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment