按钮结束运行方法的方法不同

时间:2015-05-03 21:28:55

标签: c# loops managementeventwatcher

所以我有一些代码可以检查插件和删除USB设备。

public void Main_Shown(object sender, EventArgs e)
        {
            var watcheradd = new ManagementEventWatcher();
            var queryadd = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
            watcheradd.EventArrived += new EventArrivedEventHandler(watcher_deviceadded);
            watcheradd.Query = queryadd;
            watcheradd.Start();


            var watcherremove = new ManagementEventWatcher();
            var queryremove = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
            watcherremove.EventArrived += new EventArrivedEventHandler(watcher_deviceremoved);
            watcherremove.Query = queryremove;
            watcherremove.Start();   
}

我想知道无论如何我可以在我的程序退出之前停止watchremovewatcheradd循环,以防止停止代码中的异常:

     private void Exit_Main(object sender, EventArgs e)
    {
        Process p = new System.Diagnostics.Process();
        ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo();
        si.RedirectStandardInput = false;
        si.CreateNoWindow = true;
        si.UseShellExecute = false;
        si.FileName = "adb.exe";
        si.Arguments = "kill-server";
        p = Process.Start(si);
        p.WaitForExit();

        Application.Exit();
        //EXIT APPLICATION!!!            
    }

因为Main_Shown.deviceadd.Stop();不是正确的语法或方法。 结果应该安全地停止上面的循环,然后允许程序退出而没有例外。

1 个答案:

答案 0 :(得分:0)

有一个解决方案。 所以我需要添加

 ManagementEventWatcher watcheradd = new ManagementEventWatcher();
    WqlEventQuery queryadd = new WqlEventQuery();
    ManagementEventWatcher watcherremove = new ManagementEventWatcher();
    WqlEventQuery queryremove = new WqlEventQuery();
在类之上

并将类设置为全局。所以现在它使用下面的代码退出没有问题。

`si.FileName = "adb.exe";
        si.Arguments = "kill-server";
        p = Process.Start(si);
        p.WaitForExit();
        watcherremove.Stop();
        watcheradd.Stop();
        Application.Exit();
        //EXIT APPLICATION!!`

感谢大家的帮助。