Just to prove that I am a true geek I thought I would tackle Brad Abrams latest C# quiz. The simple answer is that it won’t compile because the Thread classes constructor can now take two different delegates, ThreadStart, and ParameterizedThreadStart, and because the code uses anonymous methods – the compiler can’t figure out which delegate you mean – its ambiguious, you’ve just got to love the compiler error though.
“ Error 1 The call is ambiguous between the following methods or properties: 'System.Threading.Thread.Thread(System.Threading.ThreadStart)' and 'System.Threading.Thread.Thread(System.Threading.ParameterizedThreadStart)'”
There are a couple of ways that you can change the code to solve the problem:
There are four options because there are two different delegates, and two different ways to create them without ambiguity. But hang on a sec – Brad listed FIVE solutions, and more than one of them is different to mine. Sure Brad - you go right ahead and declare another explaining variable – you hippie! :P
The fifth one was interesting though, and I think it was supposed to be a hook that brought up some discussion, there are two to be had.
- When are anonymous methods good, when are they bad?
- How cool is new kid on the block, ParameterizedThreadStart?
I think the jury is still out on number one, but I have seen some interesting usages. However, I do have an opinion on ParameterizedThreadStart. The framework needs this, especially if you want to quickly dispatch a method on another thread with some reference data without using up a thread on the system thread pool, however I’m not going to be so quick to give up the job dispatch patterns just yet – why? Telemetry in a multi-threaded environment.
When you build an abstraction over multi-threading libraries you can allow the code executing on those threads to publish information out about their progress and activities. It also helps highlight code that operates in a multi-threaded environment because you slap them into some kind of job class.