How to invoke a method asynchronously

time to read 2 min | 387 words

A long time ago I posted about Static Reflection, here is a good use for it, asynchronous invocation without all the bother. How? It's pretty simple, actually. Let's say that I've the following method.

public void Dispatch()
{
   // Take a long time
}

If I want to run it asynchornously, I need to create a delegate, instantiate it, etc. I really hate doing this sort of mind numbing stuff just to make the compiler happy. So I thought, why wouldn't I make it do the work for me?

What follows is the easy way to run this method asynchronously. Are you ready?

((

Proc)Dispatch).BeginInvoke(null, null);

This is it.

Proc is a delegate that is defined in my Static Reflection* (and in Commons). This is making use of a new features in C# 2.0, which means that you can usually just treat a method as a delegate, if you have the correct delegate for it. I believe that it was originally intended for stuff like:

btnName.TextChange += UpdateName;

But this is a much better use of this.

* There is a whole set of them. Generic parameterized delegates, the Procs are the ones without return value, the Func has a return value.