简体   繁体   English

System.Threading.Timer回调到主线程

[英]System.Threading.Timer callback to main thread

This is my scenario: I'm doing communication between devices on a wireless network. 这是我的情况:我正在无线网络上的设备之间进行通信。 When two devices are communicating but their connection drops unexpectedly, messages are automatically buffered until they are able to connect to each other again. 当两个设备进行通信但它们的连接意外断开时,消息将自动进行缓冲,直到它们能够再次彼此连接。 This means I need to periodically (every X seconds) update a list of everyone who is available on the current network (since it's many devices connecting to many others). 这意味着我需要定期(每X秒)更新当前网络上可用的每个人的列表(因为有很多设备连接到许多其他设备)。 When some client is discovered who may have been forcefully disconnected earlier, this means some messages may be buffered for this client. 当发现某个客户端之前可能被强行断开连接时,这意味着可能为此客户端缓冲了一些消息。

Refreshing the list of devices on the network every X seconds seems like a job for System.Threading.Timer . 每X秒钟刷新一次网络上的设备列表似乎是System.Threading.Timer一项工作。 The thing is that I'm worried about data race conditions when this timer thread will try to send messages, but the main thread might try to send the remaining messages too (for a different reason). 问题是我担心此计时器线程尝试发送消息时的数据争用情况,但主线程也可能尝试发送其余消息(由于其他原因)。

So I'm wondering - can I raise an event on the main thread from within the System.Threading.Timer thread? 所以我想知道-我可以在System.Threading.Timer线程内的主线程上引发一个事件吗? Or how would I approach this otherwise, considering any method needs to work on both Windows Phone 8 and Windows 8 (Store apps). 或者考虑到任何方法都需要在Windows Phone 8和Windows 8(商店应用程序)上都可以使用的话,我将如何处理。

You could use Dispatcher.Invoke . 您可以使用Dispatcher.Invoke

See http://msdn.microsoft.com/en-us/library/system.windows.threading.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));
}

Or, as @HansPassant suggested, consider using DispatcherTimer . 或者,按照@HansPassant的建议,考虑使用DispatcherTimer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM