Using Excel Services CloseWorkbook call asynchronously

When using the Excel Service API, it is advisable the you always call CloseWorkbook() after you are done with it. This will allow your Excel Services to free resources in a predictable manner and could potentially boost your server performance and robustness.

 

That said, calling any web-service call is something that takes time. Depending on the way your server is installed, the way you access it and how much pressure it is under, this can be anywhere between 50 milliseconds to 500 milliseconds (it can also take more, but that’s only if your server is under severe stress. Since a failure on a call to CloseWorkbook() is not actionable, there is no reason for you to actually wait for it to finish so you can see if it succeeded or not. Because of that, you can always* make the call asynchronously and shave some time off the operations run time.

 

To make the call Async, you need to do two things:

  1. Make sure you do not dispose of the service proxy (if you do, non-Excel Services exceptions may occur). In some of my examples, I use the Excel Service proxy inside a using statement – if you are making use of those examples, make sure you are not employing the using statement.
  2. Call the generated CloseWorkbookAsync() method instead if the CloseWorkbook() one. You don’t need to pass in a User State object. You also don’t really need to implement the event that will be called when the method is called.

That’s it. The method will be executed asynchronously and not cost your application time.

 

* It is a good rule to never use qualifiers such as “never” and “always” when talking about software (you can use these qualifiers on meta-software rules though ;)). In this case, if your application is, for example, a console application that makes some calls to Excel Services and then exists, you may indeed want to call the synchronous version of CloseWorkbook() instead of the asynchronous one. The reason being that if you immediately exit the process after issuing an async call, there’s a good chance that call will not go through.