考虑下面的代码片段:在c#中运行异步操作。 - 基本。
if(form1.isLoggedIn)
{
//Create a wait handle for the UI thread.
//the "false" specifies that it is non-signalled
//therefore a blocking on the waitone method.
AutoResetEvent hold = new AutoResetEvent(false);
filename = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), DateTime.Now.ToString("ddMMyyhhmm") + "-" + form1.username);
Flow palm = new Flow(new FlowArguments(form1.username, filename), hold);
System.Windows.Forms.NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon();
System.Windows.Forms.ContextMenuStrip notificationIconContext = new System.Windows.Forms.ContextMenuStrip();
//Create a context menu strip
ToolStripMenuItem contextAbout = new ToolStripMenuItem("About");
ToolStripMenuItem contextExit = new ToolStripMenuItem("Exit");
//properties of notifyicon that SO dosnt care for including a event handler for the mouse click events.
//wait for the background thread to finish.
hold.WaitOne(Timeout.Infinite);
MessageBox.Show("Thankyou, exiting...");
form1.Dispose();
}
正如你看到流类是非常简单的。它只有一个正在运行的Threading.Timer。因此,在UI线程上,我必须调用WaitHandle.WaitOne()方法,否则UI线程会结束并因此结束应用程序。
我的目标:由于没有GUI,因此我想创建通知图标。它工作和一切,除了我不能点击它和它没有响应,这是因为它是在UI线程上创建的。我不能把它放在流类中,因为Flow类也在UI线程上(Flow类中的定时器在后台线程中)。
那么在Flow类中运行定时器时如何保持notifyicon响应?我认为waithandle是我的解决方案,但由于其阻塞方法,它不起作用。
任何其他想法/解决方案?
编辑:回复Rich的回答:Flow类在后台线程中,一切都以它应该的方式运行。但是,如果我不在UI线程中添加等待句柄,main()将在UI线程上结束,因此终止整个程序。 (即使在后台线程上启用了定时器)。有另一种解决等待处理的解决方案吗?因为我必须让Flow类去做它的事情。如果我把它拿出来,程序就结束了,如果我把它留在它里面,就会阻塞UI线程,因此我的notifyicon dosnt工作。
嗨,请阅读我的编辑。 – masfenix 2009-01-12 17:57:03