您的位置:首页 > 编程语言 > C#

Visual C# Office自动化Excel进程残留问题

2010-08-15 16:03 435 查看
在进行客户端编程时,经常需要进行office自动化操作,其中对于Excel使用大概又是其中最为频繁的。不过,让大家颇为郁闷的是,经常会有excel进程不能被正常关闭。不论大家怎样小心或者是单步跟踪来找问题,总是会有未被释放的com object 。我个人感觉这不能不说是office自动化的一个瑕疵,功能已经很傻瓜了,而其使用却又需要这么谨小慎微。

以前在使用VC++6.0时,就经常会遇到这个问题,最近升级到VS2010,改玩C#了,本以为由于自带的GC功能而能自动解决这个问题,没想到,还是会出现。看来是com设计的问题了。

从google的搜索结果来看,主要的解决方法无外乎两种:一种是谨小慎微,对于每个变量都予以保存,到最后记得释放;另一种则是比较野蛮了,直接kill掉残留excel进程。

方法1从理论上固然可取,我想各位肯定想正确的使用并最终完全释放掉所有涉及资源,但是由于实际操作中涉及的对象众多,难免挂一漏万,所以实际上还是会出问题。有人甚至对excel中的主要对象进行了再封装,可以自动释放对于com object的引用。

方法2看起来野蛮,但是操作简单。我在网上也看到了有些kill进程的方法,这些方法对excel进程不加区分,格杀勿论,会导致用户体验问题。但是只要提前保存自己所调用excel进程的句柄则可以不必滥杀无辜。具体实施方案如下:



using System.Runtime.InteropServices;

using System.Diagnostics;

[ DllImport ( "user32.dll" )]

private static extern uint GetWindowThreadProcessId ( IntPtr hWnd , out uint lpdwProcessId );

/// <summary> Tries to find and kill process by hWnd to the main window of the process.</summary>

/// <param name="hWnd">Handle to the main window of the process.</param>

/// <returns>True if process was found and killed. False if process was not found by hWnd or if it could not be killed.</returns>

public static bool TryKillProcessByMainWindowHwnd(int hWnd)

{

uint processID;

GetWindowThreadProcessId((IntPtr)hWnd,out processID);

if(processID ==0)

return false;

try

{

Process.GetProcessById((int)processID).Kill();

}

catch(ArgumentException)

{

return false;

}

catch(Win32Exception)

{

return false;

}

catch(NotSupportedException)

{

return false;

}

catch(InvalidOperationException)

{

return false;

}

return true;

}

使用示例:

int hWnd = xl.Application.Hwnd;

// ...

// here we try to close Excel as usual, with xl.Quit(),

// Marshal.FinalReleaseComObject(xl) and so on

// ...

TryKillProcessByMainWindowHwnd(hWnd);


      最后,给出上述解决方案的原链接:

http://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐