使用Visual Studio 2015,Visual C#windows應用程序。定時器運行在與創建它不同的線程中
我需要一個計時器,清空主線程中的隊列,因爲一些UI組件被修改。我這個編碼:
public Form1()
{
InitializeComponent();
Q = new ConcurrentQueue<amsg>();
timer = new System.Timers.Timer(100);
timer.Elapsed += timer_Elapsed;
timer.Enabled = true;
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
clsUdpMsg msg;
while (Q.TryDequeue(out msg)) handleRx(msg);
}
,但經過的事件在輔助線程執行...?
如果我把一個計時器在設計時在主窗體上生成的原型是稍有不同:
private void timer1_Tick(object sender, EventArgs e)
{
amsg msg;
while (Q.TryDequeue(out msg)) handleRx(msg);
}
但一個人在主線程上下文中執行。
這個問題延伸到任何創建一個計時器的線程;我認爲在線程中創建的計時器在同一個線程上下文中執行已用過的事件。我錯過了什麼嗎?
快速編輯:我看到這些是不同的定時器,System.Timers.Timer和Windows.Forms.Timer。那麼 - 我如何可靠地創建將在創建它們的線程中執行的定時器?
他們是2個不同的計時器。第一個來自'System.Timers','Windows.Forms.Timer'是第二個 – Plutonix
.net中有4個定時器,還有'System.Threading.Timer'和'System.Windows.Threading。DispatcherTimer'也 –