Monday 18 May 2009

Removing Process Instances - Apparently I Am Clever

A good year ago i posted on Daniweb (to whom I actively help) a code snippet for using the office interops and creating a wrapper class for them (you can see that post here). Anyway a few private comments and some posts later I received feedback that it was pretty clever, get that eh! So I thought seeing as I may need it sometime and am moving all my useful artifacts over to this blog account I would post it up. The "clever-bit" apparently is in working out a processes unique number so it can be killed later on if there are problems with it. This comes in handy when performing server side or hidden client side interactions with other interops such as Microsoft Office (creating Excel spreadsheets and such) without destroying a users existing session or other sessions that a server may be using (such as threading multiple requests).

The following code function basically works out all existing process' total for a given instance.


<summary>Function to calculate the total sum of process ID's for a given process name.</summary>
<param name="instanceName">The instance to count</param>
Private Shared Function GetTotalProcessID(ByVal instanceName As String) As Integer
For Each diaProc As System.Diagnostics.Process In System.Diagnostics.Process.GetProcessesByName(instanceName)
GetTotalProcessID += diaProc.Id
Next
End Function


This does not seem to special but when performing this before and after we can subtract the first from the second to give us our process' unique number. Bingo! The following code demonstrates this showing an example creating a Microsoft Word instance.


' Get Total before app exists
Dim totalProc As Integer = GetTotalProcessID("winword")
Dim wordApp As Word.Application = New Word.Application()
' Hide alerts and screen updating
wordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone
wordApp.ScreenUpdating = False

' Get New Total and subtract to get out ID
totalProc = GetTotalProcessID("winword") - totalProc

' ... Do some magic with the word instance ...

' When finished you should call 'worApp.Quit()'
' And also 'Marshal.ReleaseComObject(wordApp)'
' But incase that instance just wont go away... Kill it!
System.Diagnostics.Process.GetProcessById(totalProc).Kill()


So there we have it you now have the process' ID and assuming everything goes right you wont have to kill it, but for thos times everything fails you can always fall back on calling "System.Diagnostics.Process.GetProcessById().Kill()" to get rid of that pesky instance.

No comments:

Post a Comment