Monday, January 4, 2010

Threading with anonymous method

One of the enhancements to C# in version 2.0 is anonymous methods. These allow you to specify blocks of code as methods within other methods, and use those methods as delegates. You can access variables (including local variables and parameters of the "outside" method) within the anonymous method.

So with this enhancement it is now very easy to pass delegated method in a created thread.

Before you need to pass an object and cast it inside the delegated function.

for example, if you need to pass multiple strings to a delegated function, then you need to use delimeter and then parse it in delegated function, as shown in the example below.



Now with the enhancement with .Net 2.0, it easier.

Using with ThreadPool

ThreadPool.QueueUserWorkItem(delegate { d.Worker2("my string parameter"); });

or with lambda exporession

ThreadPool.QueueUserWorkItem(e => d.Worker2("my string parameter"));

Using with ParameterizedThreadStart

Thread t = new Thread(new ParameterizedThreadStart(delegate{ d.Worker("my string parameter");}));

Code Example:

No comments:

Post a Comment