为什么执行在方法中间停止?

时间:2009-08-13 00:34:40

标签: c#

插入或弹出CD时会触发以下方法。

有问题的代码如下所示。

此处的所有内容都基于使用断点逐步执行代码。

 public void CDREventArrived(object sender, EventArrivedEventArgs e)
    {
        // Get the Event object and display it
        PropertyData pd = e.NewEvent.Properties["TargetInstance"];

        if (pd != null)
        {
            ManagementBaseObject mbo = pd.Value as ManagementBaseObject;

            if (mbo.Properties["VolumeName"].Value != null)
            {
                //This line is executed.
                textBox1.Text = "test";

                //This line is not executed.  
                //While stepping through the execution, 
                //I hit F11 on the line above,   
                //hoping to get to this next line, but it never happens. 
                //The form pops back up and the step through is complete.
                label1.Text = "test";
            }
            else
            {
                //Same problem here.  Only the first line is hit.
                textBox1.Text = "test";
                label1.Text = "test";
            }
        }
    }

一个相关的问题是,虽然它确实触及代码来更改textBox1的文本属性,但实际上并未更改文本。我可以在表格上看到这一点,同时踩过断点。所以看起来它会碰到代码,但从来没有真正执行过。我想知道为什么它不会继续给定条件中的所有代码。

以下是设置委托的代码。在FormLoad上调用此方法。我在表格退出时停止了听众。

private void CreateCDRomListener()
    {
        WqlEventQuery q;
        ManagementOperationObserver observer = new
            ManagementOperationObserver();

        // Bind to local machine
        ConnectionOptions opt = new ConnectionOptions();
        opt.EnablePrivileges = true; //sets required privilege
        ManagementScope scope = new ManagementScope("root\\CIMV2", opt);

        try
        {
            q = new WqlEventQuery();
            q.EventClassName = "__InstanceModificationEvent";
            q.WithinInterval = new TimeSpan(0, 0, 1);

            // DriveType - 5: CDROM
            q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5";
            w = new ManagementEventWatcher(scope, q);

            // register async. event handler
            w.EventArrived += CDREventArrived;
            w.Start();

            // Do something usefull,block thread for testing
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

        }
        finally
        {
        }
    }

3 个答案:

答案 0 :(得分:4)

我的第一个猜测是这个回调发生在不是UI线程的线程上。试试这个:

if (InvokeRequired)
{
    Invoke(() => textBox1.Text = "test");
}
else
{
    textBox1.Text = "test";
}

答案 1 :(得分:2)

我认为在某些时候会触发例外。
我可能会在该代码中放置一个try / catch来查看是否有东西触发了异常。

答案 2 :(得分:0)

当您尝试更改早期转出的Text属性时,是否有一些文本框的事件处理程序被触发?