我目前有一个线程可以侦听来自网络的数据,然后在其上运行规则。然后我想将数据传递给GUI。我担心在GUI中发生死锁。我无法弄清楚把互斥体放在GUI一边。我也使用c#和dotnet 3.5。Winforms应该我多线程或使用事件计时器?
我想到的是 1)使用计时器来创建事件并转储线程。担心表现。 2)使用中间事件将数据复制到GUI。 3)挖掘并找出使用GUI的线程安全方式。
您认为最好的方法是什么?
编辑:这是我正在使用的解决方案。我传入更改后的元素,然后用互斥锁保护大对象。我使用帮助函数切换线程使用InvokeRequired然后BeginInvoke与委托。从阅读答案拉动,然后跟随链接,直到达到Threading in Windows Forms由Jon Skeet。
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();
}
您使用.net 2.0吗? – JoshBerke 2009-03-05 16:15:34