C# 2 has anonymous delegates. I like them. Of course, they enable advanced constructs like closures and continuations, but one of I’m a pushover for language and environment features that improve readability and maintainability of code. Before C# 2, if you wanted to perform a task on another thread, you might do something like this:
/// Do something worker callback
private void DoSomethingImpl(object callerData) {
// implementation here
. . .
}
/// Do something on a threadpool thread
private void DoSomething() {
// invoke on threadpool thread
ThreadPool.QueueUserWorkItem(new WaitCallback(DemoJob));
}
With anonymous delegates, you can just do this:
/// Do something on a threadpool thread
private void DoSomething() {
// invoke on threadpool thread
ThreadPool.QueueUserWorkItem(delegate(object o) {
// implementation here
. . .
}) ;
}
Fewer lines of code. Easier to maintain. Logic easier to follow. The pattern gets even nicer when your worker method needs arguments. For example:
/// Do something on a threadpool thread
private void DoSomething(int a, double b, SomeClass c) {
// invoke on threadpool thread
ThreadPool.QueueUserWorkItem(delegate(object o) {
// implementation here can use a, b, and c
. . .
}) ;
}
To pass the three arguments a, b, and c to a named method would require a custom class or packaging in a collection or array. I won’t show you how to do it. It is tedious, after all.






Main feed
Email subscriptions


