【发布时间】:2010-10-11 13:21:30
【问题描述】:
我目前有一个线程来侦听来自网络的数据,然后在其上运行规则。然后我想将数据传递给 GUI。我担心在 GUI 中出现死锁。我不知道将互斥锁放在 GUI 端。我也在使用 c# 和 dotnet 3.5。
我想出的是 1)使用计时器创建事件并转储线程。担心性能。 2) 使用中间事件将数据复制到 GUI。 3) 深入研究并找出使用 GUI 的线程安全方式。
你认为最好的方法是什么?
编辑:这是我正在使用的解决方案。我传入更改的元素,然后用互斥锁保护大对象。我使用辅助函数使用 InvokeRequired 然后 BeginInvoke 与委托切换线程。从阅读答案中提取,然后点击链接,直到通过Jon Skeet 到达Threading in Windows Forms。
delegate void UInt32ParameterDelegate(UInt32 n);
public void UpdateLocation(UInt32 n)
{
if (InvokeRequired)
{
// We're not in the UI thread, so we need to call BeginInvoke
BeginInvoke(new UInt32ParameterDelegate(UpdateLocation), new object[] { n });
return;
}
// Must be on the UI thread if we've got this far
this.engine.location.UpdateBusy.WaitOne();
// do the work in here
this.engine.location.UpdateBusy.ReleaseMutex();
}
【问题讨论】:
标签: c# winforms multithreading user-interface