Last active
December 24, 2015 13:49
-
-
Save mikehadlow/6808100 to your computer and use it in GitHub Desktop.
The many ways to start a thread in .NET. Can you think of any more?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace Mike.Spikes.Threading | |
{ | |
public class ManyWaysToStartAThread | |
{ | |
public void WithThread() | |
{ | |
// explicit thread creation doesn't run on the threadpool. | |
var thread = new Thread(() => | |
{ | |
Console.WriteLine("Hello from {0}", Thread.CurrentThread.Name); | |
}) | |
{ | |
Name = "my thread" | |
}; | |
thread.Start(); | |
Console.Out.WriteLine("Hello from the calling thread {0}", Thread.CurrentThread.ManagedThreadId); | |
thread.Join(); | |
} | |
public void WithDelegate() | |
{ | |
// delegates expose the APM. Thread runs on the threadpool. | |
Action myDelegate = () => | |
{ | |
Console.WriteLine("Hello from the delegate {0}", Thread.CurrentThread.ManagedThreadId); | |
}; | |
var asyncResult = myDelegate.BeginInvoke(state => | |
{ | |
Console.Out.WriteLine("Hello from the async callback"); | |
}, null); | |
Console.Out.WriteLine("Hello from the calling thread {0}", Thread.CurrentThread.ManagedThreadId); | |
myDelegate.EndInvoke(asyncResult); | |
} | |
public void WithThreadpool() | |
{ | |
var autoResetEvent = new AutoResetEvent(false); | |
ThreadPool.QueueUserWorkItem(state => | |
{ | |
Console.WriteLine("Hello from the thread pool {0}", Thread.CurrentThread.ManagedThreadId); | |
autoResetEvent.Set(); | |
}); | |
Console.Out.WriteLine("Hello from the calling thread {0}", Thread.CurrentThread.ManagedThreadId); | |
autoResetEvent.WaitOne(); | |
} | |
public void WithTPL() | |
{ | |
var task = Task.Factory.StartNew(() => | |
{ | |
Console.WriteLine("Hello from the task {0}", Thread.CurrentThread.ManagedThreadId); | |
}); | |
Console.Out.WriteLine("Hello from the calling thread {0}", Thread.CurrentThread.ManagedThreadId); | |
task.Wait(); | |
} | |
public void WithParallel() | |
{ | |
var autoResetEvent = new AutoResetEvent(false); | |
Parallel.Invoke(() => | |
{ | |
Console.WriteLine("Hello from the thread {0}", Thread.CurrentThread.ManagedThreadId); | |
autoResetEvent.Set(); | |
}); | |
Console.Out.WriteLine("Hello from the calling thread {0}", Thread.CurrentThread.ManagedThreadId); | |
autoResetEvent.WaitOne(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using an instance of the System.Threading.Timer type: