使用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'也 –