Sunday, September 18, 2011

Difference between Thread and ThreadStart delegate

I have been working since .Net 1.1, the way we create/spawn threads is

1. Create a ThreadStart delegate for parameter less target method or Create a ParameterizedThreadStart delegate for target accepting parameters. 2. The next step was to create a Thread object and pass this delegate. 3. Lastly call the Start method to execute the thread.

This was the norm till .Net 2.0. What seems confusing now is that, from ver. 2.0 we can directly pass the target to the Thread's constructor and call the Start method !!!

Well this is due to the enhancement which .Net 2.0 onwards have to offer. Instead of going the way we did above in 1.1, the compiler now invokes the appropriate delegate based on the target passed.

So technically speaking both the approaches below are the same.

1. ThreadStart ts = new ThreadStart(Somework); // .Net 1.1 way of creating threads Thread t = new Thread(ts); t.Start();

2. Thread t = new Thread(Somework); // .Net 2.0 onwards way of creating threads t.Start();

Happy coding :)

No comments: