Geeks With Blogs
Rohit Gupta Engaging talk on Microsoft Technologies ....My Resume

We already know that we can pass state into to Threads in 2 ways:

1. using ParameterizedThreadStart delegate

2.using global variables(reference or value types) accessible to the main thread as well the instantiated thread. This is also the way to share data amonst multiple threads. Infact the most common way to share data between threads is using static variables where application wide scope is desired.

3.using Thread.QueueUserWorkItem ... This differs from Parameterized ThreadStart delegate since it uses threads from a preconfigured ThreadPool instead of manually creating threads

There is another cool method to pass information to threads is via anonymous methods. For e.g.
static void Main
    string mainMessage = "Hello from Main !!!";
    Thread t = new Thread(delegate() { Print(mainMessage);});
static void Print(string message)
Advantage of using this technique is that, it provides strongly typed access to the parameters passed to the thread. The Target Method can accept any number of arguments, and no casting is required (unlike Parameterized Start where the passed state is an “object”) . The flip side, though, is that you must keep outer-variable semantics in mind Posted on Monday, October 13, 2008 3:19 PM | Back to top

Comments on this post: Passing state to threads via anonymous calls

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Rohit Gupta | Powered by: