senpost
4/20/2011 - 4:14 AM

Different ways to create and run thread

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
System.Threading.Tasks.Task.Factory.StartNew (Go);
...
static void Go()

//Generic Task class
// Start the task executing:
Task<string> task = Task.Factory.StartNew<string>
    ( () => DownloadString ("http://www.linqpad.net") ); 
// 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;

//Prior to TPL v4.0, Use ThreadPool.QueueUserWorkItem and asynchronous delegates
//Example for ThreadPool.QueueUserWorkItem
//Go method should be like WaitCallback
//public delegate void WaitCallback(Object state)
ThreadPool.QueueUserWorkItem (Go);
ThreadPool.QueueUserWorkItem (Go, 123);

//asynchronous delegate 
Func<string, int> method = Work;
//The final argument to BeginInvoke is a user state object that populates the AsyncState property of IAsyncResult. 
//It can contain anything you  like; in this case, we’re using it to pass the method delegate to the completion callback, 
//so we can call EndInvoke on it.
method.BeginInvoke ("test", Done, method);
//...
static int Work (string s) { return s.Length; }
static void Done (IAsyncResult cookie)
{
  var target = (Func<string, int>) cookie.AsyncState;
  int result = target.EndInvoke (cookie);
  Console.WriteLine ("String length is: " + result);
}