I'm trouble with the exception handling. Specifically, I create a System.Diagnostic.Process object from the process identifier (PID), then I use it to execute my algorithm. I've noticed that this class throw InvalidOperation and ArgumentException exception when accessing to different properties, because the process has already exited while I'm accessing to the Process instance.
However, the algorithm uses other function which throw the same exceptions. The following code is the one which has raised the problem:
XmlWindow mWindow = new XmlWindow(new IntPtr(args.Message.GetContent<Int64>()));
Process mWindowProcess = mWindow.GetProcess();
XmlProcessInstance mWindowProcessInstance = null;
XmlProcessLayout pLayout = null;
Log(mWindow);
lock (mCoreData.ProcessList) {
try {
// Ensure matching XmlProcess
mCoreData.ProcessList.EnsureProcessManagement(mWindowProcess);
} catch (System.ComponentModel.Win32Exception eWin32Exception) {
sLog.WarnFormat("Unable to manage window creation ({0}, error code {1}).", eWin32Exception.Message, eWin32Exception.NativeErrorCode);
break;
}
}
lock (mCoreData.LayoutList) {
// Unmanaged process?
if (mCoreData.LayoutList.IsManagedProcessInstance(mWindowProcess) == false) {
lock (mCoreData.UnmanagedLayout) {
// Force process management
if ((mWindowProcessInstance = mCoreData.UnmanagedLayout.GetProcessInstance((uint)mWindowProcess.Id)) == null) {
mWindowProcessInstance = mCoreData.UnmanagedLayout.ManageProcessInstance((uint)mWindowProcess.Id, mCoreData.ProcessList);
sLog.DebugFormat("Layout \"{0}\" will manage explictly the process \"{1}\" ({2}).", mCoreData.UnmanagedLayout.Name, mWindowProcessInstance.ApplicationName, mWindowProcessInstance.InstanceId);
}
}
} else {
// Find the (managed) process instance
mWindowProcessInstance = mCoreData.LayoutList.GetProcessInstance((uint)mWindowProcess.Id);
}
}
Log(mWindowProcessInstance);
// Ensure window match
mWindowProcessInstance.ProcessAssociation.AssociatedItem.LearnWindowMatching(mWindow);
// Register process instance window
mWindowProcessInstance.LearnWindowTemplating(mWindow);
mWindowProcessInstance.Windows.Add(mWindow);
// Apply window template (if any)
mWindowProcessInstance.ApplyTemplateWindow(mWindow);
The problem is how to manage the InvalidOperationException exception. The code above doesn't work, since the exception could be thrown by SomeFunction, instead by accessing the Process instance; I need to handle only those exception thrown by the mWindowProcess.
Of course I need a big one try/catch statement, because the usage of the variable mWindowProcess is very intensive
How this could be solved correctly?