How do I run a simple bit of code in a new thread?

Tim M picture Tim M · Dec 12, 2008 · Viewed 425.6k times · Source

I have a bit of code that I need to run in a different thread than the GUI as it currently causes the form to freeze whilst the code runs (10 seconds or so).

Assume I have never created a new thread before; what's a simple/basic example of how to do this in C# and using .NET Framework 2.0 or later?

Answer

Ed Power picture Ed Power · Nov 28, 2012

Good place to start reading is Joe Albahari.

If you want to create your own thread, this is as simple as it gets:

using System.Threading;
new Thread(() => 
{
    Thread.CurrentThread.IsBackground = true; 
    /* run your code here */ 
    Console.WriteLine("Hello, world"); 
}).Start();