回调到主线程的timer

本文关键字:timer 线程 回调 | 更新日期: 2023-09-27 18:12:33

这是我的场景:我正在无线网络上进行设备之间的通信。当两个设备正在通信但它们的连接意外断开时,消息将自动缓冲,直到它们能够再次相互连接。这意味着我需要定期(每隔X秒)更新当前网络上可用的所有人的列表(因为它是许多设备连接到许多其他设备)。当发现某个客户端之前可能被强制断开连接时,这意味着该客户端的一些消息可能被缓冲。

每X秒刷新一次网络上的设备列表似乎是System.Threading.Timer的工作。问题是,当这个计时器线程尝试发送消息时,我担心数据竞争条件,但是主线程也可能尝试发送剩余的消息(出于不同的原因)。

所以我想知道-我可以从System.Threading.Timer线程内引发主线程上的事件吗?或者,考虑到任何方法都需要同时适用于Windows Phone 8和Windows 8(商店应用),我该怎么做呢?

回调到主线程的timer

您可以使用Dispatcher.Invoke

见http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.invoke:

private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    // Place delegate on the Dispatcher. 
    this.Dispatcher.Invoke(DispatcherPriority.Normal,
        new TimerDispatcherDelegate(TimerWorkItem));
}

或者,正如@HansPassant建议的那样,考虑使用DispatcherTimer