考虑以下代码段:
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();
}
如您所见,FLOW 类非常简单。它只有一个正在运行的 Threading.Timer。因此,在 UI 线程上,我必须调用 WaitHandle.WaitOne() 方法,否则 UI 线程完成并因此结束应用程序..
我的目标:由于没有 GUI,我想创建一个通知图标。它可以工作,一切正常,除了我无法点击它并且它没有响应,这是因为它是在 UI 线程上创建的。我不能把它放在流类中,因为流类也在 UI 线程上(流类中的计时器在后台线程中)。
那么如何在 Flow 类中运行计时器时让我的 notifyicon 保持响应?我认为 waithandle 是我的解决方案,但由于它是一种阻塞方法,所以它不起作用。
还有其他想法/解决方案吗?
编辑:对 Rich 的回答的回应: Flow 类在后台线程上,一切都按照它应该的方式运行。但是,如果我不在 UI 线程中添加等待句柄,则 main() 在 UI 线程上完成,因此终止整个程序。(即使在后台线程上启用了计时器)。是否有另一种解决方案来等待处理?因为我必须把它留给 Flow 类来做它的事情。如果我把它拿出来,程序就会结束,如果我把它留在里面会阻塞 UI 线程,因此我的 notifyicon 不起作用。