如何保护来自另一个线程的数据以在控件上使用?
我有一个库,它使用来自异步 tcp 操作的事件数据提供服务。 当在 UI 上收到这些数据后在控件中使用这些数据时,我收到了跨线程操作异常。如何在图书馆的使用者获得要在其控件上显示的数据之前解决此问题。所以基本上我需要将数据扔到他自己的线程中使用该库?
与带有链接文件的紧凑框架使用的代码相同。
我在库内部使用此方法和帮助控件来说明是否需要调用但它不起作用。
public static void InvokeIfNecessary(Control control, Action setValue)
{
if (control.InvokeRequired)
{
control.Invoke(setValue);
}
else
{
setValue();
}
}
使用事件向使用该库的用户提供数据的示例代码。
if (OnClientChangeConnection != null) SafeData.InvokeIfNecessary(_helpControl, () => OnClientChangeConnection(ConnectedClients, requestClientInfo)); // ConnectedClients is an integer and requestClientInfo is a List<ClientInfo> class type.
谢谢。
I have a library that serves using events data came in from async tcp operations.
When using those data in controls after they received on the UI though I get Cross-Thread Opration exception. How to solve this problem before the consumer of the library gets the data to show on his controls. So basically I need to throw the data to his own thread where using the library?
The same code used for the compact framework with linked files.
I'm using inside the library this method with a help Control to say if invoke is required but its not working.
public static void InvokeIfNecessary(Control control, Action setValue)
{
if (control.InvokeRequired)
{
control.Invoke(setValue);
}
else
{
setValue();
}
}
A sample code using an event to serve data to the user using the library.
if (OnClientChangeConnection != null) SafeData.InvokeIfNecessary(_helpControl, () => OnClientChangeConnection(ConnectedClients, requestClientInfo)); // ConnectedClients is an integer and requestClientInfo is a List<ClientInfo> class type.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行此操作的正确方法是使用 SynchronizationContext 对象。我已经包含了示例代码。基本上,您要做的就是将线程任务包装在一个类中,该类可以保存对主线程提供的同步上下文对象和回调的引用,然后在工作结束后调用这些对象。
这是一个简单的形式:
这是一个具有线程任务的类
The proper way to do this is to use the SynchronizationContext object. I have included sample code. Basically what you have to do is wrap your thread task in a class that can save a reference to a synchronization context object and callback supplied by the main thread then it calls those after the work is down.
This is a simple form:
This is a class that has the thread task
您可以从 UI 线程保存对
SynchronizationContext.Current
的引用,然后调用其Post
或Send
方法在 UI 线程上运行代码。You can save a reference to
SynchronizationContext.Current
from the UI thread, then call itsPost
orSend
methods to run code on the UI thread.