考慮下面的代碼片段:在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