Skip to content

Instantly share code, notes, and snippets.

@iraSenthil
Created April 20, 2011 04:14
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save iraSenthil/930328 to your computer and use it in GitHub Desktop.
Save iraSenthil/930328 to your computer and use it in GitHub Desktop.
Different ways to create and run thread
//Method with no parameter - ThreadStart Delegate
Thread t = new Thread (new ThreadStart (TestMethod));
t.Start();
void TestMethod() {}
//Method with a parameter - ParameterizedThreadStart Delegate
Thread t = new Thread (new ThreadStart (TestMethod));
t.Start(5);
t.Start("test");
void TestMethod(Object o) {}
//lambda expression
Thread t = new Thread ( () => TestMethod("Hello") );
t.Start();
void TestMethod(string input) {}
//lambda expression for smaller thread methods
new Thread (() =>
{
Console.WriteLine ("I'm running on another thread!");
Console.WriteLine ("This is so easy!");
}).Start();
//anonymous methods C# 2.0
new Thread (delegate()
{
Console.WriteLine ("I'm running on another thread!");
}).Start();
//Task Parallel Libray
static void Main()
{
System.Threading.Tasks.Task.Factory.StartNew (Go);
}
static void Go()
{
Console.WriteLine ("Hello from the thread pool!");
}
//Generic Task class
static void Main()
{
// Start the task executing:
Task<string> task = Task.Factory.StartNew<string>
( () => DownloadString ("http://www.linqpad.net") );
// We can do other work here and it will execute in parallel:
RunSomeOtherMethod();
// When we need the task's return value, we query its Result property:
// If it's still executing, the current thread will now block (wait)
// until the task finishes:
string result = task.Result;
}
static string DownloadString (string uri)
{
using (var wc = new System.Net.WebClient())
return wc.DownloadString (uri);
}
//Prior to TPL v4.0, Use ThreadPool.QueueUserWorkItem and asynchronous delegates
//Example for ThreadPool.QueueUserWorkItem
static void Main()
{
ThreadPool.QueueUserWorkItem (Go);
ThreadPool.QueueUserWorkItem (Go, 123);
Console.ReadLine();
}
static void Go (object data) // data will be null with the first call.
{
Console.WriteLine ("Hello from the thread pool! " + data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment