Skip to content

Instantly share code, notes, and snippets.

@yalayabeeb
Created December 26, 2015 09:50
Show Gist options
  • Save yalayabeeb/765379e6fb4e4565fa19 to your computer and use it in GitHub Desktop.
Save yalayabeeb/765379e6fb4e4565fa19 to your computer and use it in GitHub Desktop.
Different methods on how to use threads. It also shows which methods wait for the jobs to finish before performing the next block of code and which don't.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadingExample
{
class ThreadingExample
{
private static void Method1()
{
Console.WriteLine("Method 1 started... using (Thread.Start)");
for (int i = 0; i < 5; i++)
{
Thread thread = new Thread(x => { Console.WriteLine(x); });
thread.Start(i);
}
Console.WriteLine("Method 1 finished...");
}
private static void Method2()
{
Console.WriteLine("Method 2 started... using (Parallel.For)");
Parallel.For(0, 5, i =>
{
Console.WriteLine(i);
});
Console.WriteLine("Method 2 finished...");
}
private static void Method3()
{
Console.WriteLine("Method 3 started... using (Parallel.Invoke)");
Action[] actions = new Action[5];
for (int i = 0; i < 5; i++)
{
int number = i;
actions[i] = () => { Console.WriteLine(number); };
}
Parallel.Invoke(actions);
Console.WriteLine("Method 3 finished...");
}
private async static void Method4()
{
Console.WriteLine("Method 4 started... using (Task.Run)");
await Task.Run(() =>
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
});
Console.WriteLine("Method 4 finished...");
}
private static void Method5()
{
Console.WriteLine("Method 5 started... using (Task.Factory.StartNew)");
Task[] tasks = new Task[5];
for (int i = 0; i < 5; i++)
{
int number = i;
tasks[i] = Task.Factory.StartNew(() => { Console.WriteLine(number); });
}
Task.WaitAll(tasks);
Console.WriteLine("Method 5 finished...");
}
private static void Method6()
{
Console.WriteLine("Method 6 started... (using ThreadPool.QueueUserWorkItem)");
for (int i = 0; i < 5; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(x => Console.WriteLine(x)), i);
}
Console.WriteLine("Method 6 finished...");
}
static void Main(string[] args)
{
Method1();
Method2();
Method3();
Method4();
Method5();
Method6();
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment