CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Grant Killian's Blog

No, this has nothing to do with beer -- but maybe it should?

FireAndForget

In the blogging mood today, so I figured I'd blog a useful code snippet.  Doing Fire-And-Forget operations, the one-way method calls that don't return a value and you don't want to block the main application thread, are exceedingly easy in .Net (unless I'm doing things wrong!).  Doing asynchronous operations like this used to be tricky, but not anymore.  

No, you don't want to use BeginInvoke and risk memory leaks . . . instead, you're better off using the QueueUserWorkItem method of the ThreadPool object.  Syntax looks like this:

WaitCallback cb= new WaitCallback( FireAndForgetMethod ) ;
ThreadPool.QueueUserWorkItem( cb ) ;

You'll need to import the System.Threading namespace for the above to compile.  You also need a FireAndForgetMethod like this:

private void FireAndForgetMethod( object o ){
  //code statements to run asynchronously . . .
} 

I use this sort of approach to send batches of email notifications, perform lengthly sql report operations, and other processing that doesn't need to run synchronously with the flow of the web application (this would certainly also work in a WinForms application).

Just did a quick google search and turned up this nicely packaged FireAndForget example too; it's a bit more involved, but at the heart uses QueueUserWorkItem in conjunction with a little nice Reflection.  It's worth checking out!



Comments

Jon Galloway said:

Agree. I've started doing this recently and it's been working well. Nice writeup.
# July 21, 2004 9:09 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add
Check out Devlicio.us!