c pound

I reject your reality and substitute my own!
posts - 46, comments - 46, trackbacks - 40

My Links

News

Archives

Image Galleries

Blog Communities

Blog is a stupid word

Lunch Hour

Resources

Asynchronous Anonymous Methods

Anonymous methods are a great new feature in .Net 2. Another great new feature is the ParameterizedThreadStart delegate. Since the ParameterizedThreadStart delegate is just a delegate, these two concepts can be combined to effectively create an asynchronous anonymous method – an anonymous thread, if you will. You can spin off a chunk of code to run asynchronously without having to put it into a separate function. Check out the following code:

 

private void AddAsync(int a, int b)

{

      //Define the code we want to run asynchronously.

      // Note that an anonymous delegate works just

      // as well as a ParameterizedThreadStart

      Thread t = new Thread(delegate(object paramArray)

      {

            //get the data we passed into the thread

            object[] param = paramArray as object[];

 

            //do your long-running process here (this part runs asynchronously)

            Thread.Sleep(1000);

            int result = (int)param[0] + (int)param[1];

 

            //when we're done with our asynchronous processing, hit the callback function

            this.Invoke(new AdditionDoneDelegate(AdditionDone), new object[] { result });

      });

 

      //start running the asynchronous code

      t.Start(new object[] { a, b });

}

 

private delegate void AdditionDoneDelegate(int result);

private void AdditionDone(int result)

{

      //this gets called when your asynchronous processing is done

      MessageBox.Show(result.ToString());

}

 

Another cool application for this is to create a partially asynchronous function. You can enclose a long running data access operation, for example, within an anonymous thread and use a non-blocking wait (a mutex) to keep the rest of the function from running until the operation is complete. That’s right, you can make just part of your function run asynchronously:

 

private void AddPartiallyAsync(int a, int b)

{

      int result = 0;

      Mutex mutex = new Mutex();

 

      Thread t = new Thread(delegate()

      {

            //do your long-running process here (this part runs asynchronously)

            Thread.Sleep(1000);

            result = a + b;

 

            //when we're done with our asynchronous processing, release the mutex

            mutex.ReleaseMutex();

      });

 

      //start running the asynchronous code

      t.Start(new object[] { a, b });

 

      //non-blocking-wait here until the thread is done

      mutex.WaitOne();

 

      //continue the function here...

      MessageBox.Show(result.ToString());

}

 

Notice that the code inside the anonymous asynchronous method can access variables defined in the surrounding function. I fully expected there to be scoping that would prevent this. But, amazingly, it works. However, I wouldn’t be surprised if this behavior was eliminated in a later version of the framework. Another surprising part of all this is how well the debugger handles it. Simply amazing!

Print | posted on Monday, August 21, 2006 8:17 AM |

Feedback

Gravatar

# re: Asynchronous Anonymous Methods

Yeah, pretty cool stuff for sure. I've been delving deep into reflection lately, building a dynamic add-in system, and have found a use for an anonymous delegate. I'm skeptical of using variables that aren't globally scoped, though. Your example calls the delegate from within the same method as its defined, so you won't run into problems there. But what happens when you call it from a method where those variables aren't defined? I think we need to be careful, because I doubt the compiler will be able to catch errors like this. Have you checked into any of this further?
8/29/2006 11:14 AM | Dan Vanderboom
Gravatar

# re: Asynchronous Anonymous Methods

Hey Dan,

The short answer is no. I haven't checked into any of this further. I probably will at some point. But, in the meantime, I would encourage you to try something cool and let me know how it goes. My longer answer would consist of the following warnings and advise based on naught but your words and my own admittedly limited experience. First, don’t assume that I know what I’m talking about. Well actually, go ahead and do that (it’s very gratifying). But, don’t assume that you won’t run into problems at any particular point just because I didn’t. Frankly, I was amazed at the apparent ability to access variables defined outside the scope of a delegate without needing to explicitly pass in some reference. You might discover that delegates can do the same thing with globally scoped variables. Second, it is very unlikely that this is an anomalous behavior. Some very smart person (more likely a whole group of smarties) at Microsoft decided that you should be able to do this. In fact, you could probably look through the language spec and find exact specifications for this behavior. And I absolutely guarantee that the compiler will be able to handle anything in the spec. What you might run into is thread safety issues or other problems that might throw exceptions at runtime. What I found most amazing is the ability of the debugger to display coherent information about those runtime errors (including stack-trace), which leads me to believe that this really is a well-defined behavior of anonymous delegates. Third, always be careful. It takes way less overall effort than being sloppy now and discovering at some later date that you shouldn’t have been. ;)
8/29/2006 12:06 PM | Dan Koster
Gravatar

# re: Asynchronous Anonymous Methods

Thanks.

Whery help me...
2/17/2009 2:10 PM | Olga
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: