日期:2014-05-20  浏览次数:20878 次

C# 使用到了COM interop后程序不能正常退出的问题
大家好,
我的程序中使用到了windows   media   player   ActiveX组件,定义如下:
private   AxWMPLib.AxWindowsMediaPlayer   Player;
它在InitializeComponent中被初始化,并且被加入form的control集中
this.Controls.Add(this.Player);

form上有另外一个system.windows.forms.timer组件,它每隔一段时间就会调用t_Tick方法
void   t_Tick(object   sender,   EventArgs   e)

在该方法中,我判断一组条件,然后决定是否退出程序,这组条件对该问题没有影响,所以我就不说了。如果条件为真,那么就会执行如下代码
this.Dispose(true);
GC.SuppressFinalization();

我的Dispose是这样的
protected   override   void   Dispose(   bool   disposing   )
{
                        if   (disposing)
                        {
                                if   (components   !=   null)
                                {
                                        components.Dispose();
                                }
                        }
                        try
                        {
                                //   remove   the   player   from   form   control   list,   so   the   form   could   be   disposed
                                this.Controls.Remove(Player);
                                //   release   the   player   com   object
                                Marshal.ReleaseComObject(Player.GetOcx());
                                base.Dispose(disposing);
                        }
                        catch
                        {
                        }
}

我在其中用ReleaseComObject方法释放掉COM组件。

Dispose被执行完之后,就会执行到Main函数
static   void   Main(string[]   args)  
{
                        //   Adds   event   handler   to   catch   any   exceptions   that   happen
                        AppDomain.CurrentDomain.UnhandledException   +=   new   UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                        try
                        {