Expert Texture Home Contact me About Subscribe Digipede Connect on LinkedIn rwandering on Twitter rwandering on FriendFeed

rwandering.net

The blogged wandering of Robert W. Anderson

Anonymous delegates are so practical

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.

Tags: ,

    Trackback

2 Comments »

    Bhavesh Patel wrote @ December 5th, 2006 at 3:14 am

I agree with you mate, C# v2 had made easier to update another thread from one thread. However, the downside is also quite obvious. Recently, I was testing progressBar control. I was updating progressbar in the loop inside thread using anonymous delegate method. Comparing it with normal progressbar update (without using delegate) the thread update is heck lot slower.

    geeks wrote @ August 13th, 2009 at 2:08 am

Humm… interesting,

Do you know if they have improved this fiture in c#3.5?

Thanks

Your comment

HTML-Tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>