I’ve been having an extremely strange issue with a custom application. Basically the application is a form that displays to the user so they can select some options relating to how they want to print a document in Word. The form then goes off and does a few things with the printer driver and prints the document as required.

For some strange reason the form started playing up recently, and users were reporting that it was locking up sometimes, and the only way you could close it was to end the WinWord process in Task Manager which is a little drastic!

With a bit of debugging (and luckily being able to replicate the issue) I found the problem code was calling the DocumentPropertiesA function from winspool.drv. This was the part of the code that was updating the printer driver with the new settings. All of a sudden the call was not returning in some instances, but in a strange twist execution was returned to the form. No exception was returned. I enabled all the controls on the form to test further, and it turns out the form was indeed active again, and the buttons would work, but you could not close the form.

A bit of research reveals you cannot close a form if there is another event still running. So I guess the code running on the OK button event was considered to be still running.

If I clicked on the OK button again, the same code would run, but at the same line of troublesome code would actually return an AccessViolationException error, and you could not continue the code.

So a bit more research and yes, AccessViolationException is bad, and your code should stop.

But here’s where it gets interesting. In versions of .Net 3.5 and earlier, an AccessViolationException would get passed back to the CLR and you could trap it. As of version 4 it does not. Well thanks for that Microsoft. You can read all about it here. That was like trying to find a needle in a haystack.

Turns out the fix is pretty simple. In the class that was running, I added the following imports statement

Imports System.Runtime.ExceptionServices

Then on the actual sub that was running, I added the following attribute

<HandleProcessCorruptedStateExceptions()>
Public Sub Update()

And voila, the TRY CATCH around the problem line picks up the exception.

I can now catch the problem. Turns out it’s not fatal in this case, and the code can keep running, and even more strangely, it works. I suspect there is still another problem that needs a little more investigation, but I’m now back to a print dialog form that appears to work the same as before which no longer locks up. So happy users, and happy developer.

If you feel like reading more on exceptions, then here’s a little more light reading that you may find interesting, I know I did. http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035

© Copyright - Mosmar