c#EventArrivedEventHandler卡在无限循环中,无法引用观察者

时间:2011-09-04 03:48:26

标签: c# multithreading event-handling

过去一周我用谷歌搜索了这个问题,这让我很平静!请帮助... EventArrivedEventHandler陷入循环,如果我停止它,那么它将不会捕获事件。但是当我使用一个处理程序方法时,线程仍然专注于循环,并且不会关注我正在尝试在处理程序中创建的新表单!奇怪的是,如果我只是使用一些小的东西,比如MessageBox,它不会引起问题,只是尝试实例化一个表单会导致按钮不能绘制。然后程序停止响应后不久。如果您想知道表单代码的位置,它只是.NET制作的标准表单,除了事件处理程序之外,它在代码中的其他地方都可以使用。

谢谢!

class MainClass
{
    public static void Main()
    {
        TaskIcon taskbarIcon;
        EventWatch myWatcher;

        taskbarIcon = new TaskIcon();
        taskbarIcon.Show();

        myWatcher = new EventWatch();
        myWatcher.Start();

        Application.Run();
    }
}

public class TaskIcon
{
    public void Show()
    {
        NotifyIcon notifyIcon1 = new NotifyIcon();
        ContextMenu contextMenu1 = new ContextMenu();
        MenuItem menuItem1 = new MenuItem();
        MenuItem menuItem2 = new MenuItem();

        contextMenu1.MenuItems.AddRange(new MenuItem[] { menuItem1, menuItem2 });

        menuItem1.Index = 0;
        menuItem1.Text = "Settings";
        menuItem1.Click += new EventHandler(notifyIconClickSettings);

        menuItem2.Index = 1;
        menuItem2.Text = "Exit";
        menuItem2.Click += new EventHandler(notifyIconClickExit);

        notifyIcon1.Icon = new Icon("app.ico");
        notifyIcon1.Text = "Print Andy";
        notifyIcon1.ContextMenu = contextMenu1;
        notifyIcon1.Visible = true;
    }

    private static void notifyIconClickSettings(object Sender, EventArgs e)
    {
        MessageBox.Show("Settings Here");
    }

    private static void notifyIconClickExit(object Sender, EventArgs e)
    {
        //taskbarIcon.Visible = false; // BONUS QUESTION: Why can't I hide the tray icon before exiting?

        Application.Exit();
    }
}

public class EventWatch
{
    public void Start()
    {
        string thisUser = WindowsIdentity.GetCurrent().Name.Split('\\')[1];

        WqlEventQuery query = new WqlEventQuery();

        query.EventClassName = "__InstanceCreationEvent";
        query.Condition = @"TargetInstance ISA 'Win32_PrintJob'";
        query.WithinInterval = new TimeSpan(0, 0, 0, 0, 1);

        ManagementScope scope = new ManagementScope("root\\CIMV2");
        scope.Options.EnablePrivileges = true;

        ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);

        watcher.EventArrived += new EventArrivedEventHandler(showPrintingForm);

        watcher.Start();
    }
    void showPrintingForm(object sender, EventArrivedEventArgs e)
    {
        // MessageBox.Show("This will draw just fine");

        Form1 myForm;
        myForm = new Form1();
        myForm.Show(); // This causes a hangup
    }
}

1 个答案:

答案 0 :(得分:0)

我的猜测是ManagementEventWatcher从与UI线程不同的线程调用EventArrived处理程序。然后在该线程上执行showPrintingForm并从与UI线程不同的不同线程访问UI。您需要将代码封送回UI线程。