Skip to content

Instantly share code, notes, and snippets.

@mikehadlow
Last active December 24, 2015 13:49
Show Gist options
  • Save mikehadlow/6808100 to your computer and use it in GitHub Desktop.
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?
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();
}
}
}
@moodmosaic
Copy link

Using an instance of the System.Threading.Timer type:

public void WithTimer()
{
    new System.Threading.Timer(_ =>
        Console.WriteLine("Hello from the timer {0}", Thread.CurrentThread.ManagedThreadId),
        null,
        0,
        Timeout.Infinite);

    Console.Out.WriteLine("Hello from the calling thread {0}", Thread.CurrentThread.ManagedThreadId);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment