Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Type-Strong Asynchronous Execution

0.00/5 (No votes)
5 Jan 2008 1  
Executing a method asynchronously with typed parameters.

Introduction

This static class allows the programmer to run a method asynchronously with a single line of code with typed arguments.

Background

Sometimes, a programmer just want some work to be done in the background, and the .NET framework provides several ways of doing just that. You can start a thread and make it call a function, or you can use the ThreadPool.QueueUserWorkItem, but I always felt it was kind of messy. Using ThreadPool forces you to use a WaitCallback delegate if you want to specify any parameters, these need to be boxed into an object and unboxed in the WaitCallback function called.

So, what I wanted was a simple function to call, Util.RunAsync(function, arg1,arg2,arg3...), in a sort of fire and forget way.

Using the Code

The static class Util contains an overloaded function called RunAsync. It is used as such:

public static void Main(string[] args)
{
    string someString = "Hello There";
    int someInteger = 42;
    DateTime someTime = DateTime.Now;

    Util.RunAsync(Function1, someString, someInteger, someTime);
}

public static void Function1(string aString, int anInteger, DateTime time)
{
    Console.WriteLine("{0} {1} {2}", aString, anInteger, time);
}

Points of Interest

The functionality is achieved using the ThreadPool.QueueUserWorkItem the function, and its arguments are wrapped in an ActionJob object that has a subclass for each amount of arguments usable with Util.RunSync. Because it is based on the Action delegate and the generic versions of it Action<T>, Action<T,V>, Action<T,V,X>, and Action<T,V,X,Y>, it can only execute functions with at most four arguments.

You should be able to change the code to work as a Work Queue for invoking with Windows Forms. Instead of running ThreadPool.QueueUserWorkItem, you could do something like this:

public static void DoInvoke<T, V, X, Y>(
              this System.Windows.Forms.Control control, 
              Action<T, V, X, Y> function, T a, V b, X c, Y d)
{
    if (control.InvokeRequired)
    {
        control.Invoke(function, a, b, c, d);
    }
    else
    {
        function(a, b, c, d);
    }
}

Conclusion

That's it. I like this little convenience, and I hope you do too :)

History

  • 5 January 2008: Article submitted.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here