如何保护来自另一个线程的数据以在控件上使用?

发布于 2024-11-07 10:22:04 字数 743 浏览 0 评论 0原文

我有一个库,它使用来自异步 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

东风软 2024-11-14 10:22:04

执行此操作的正确方法是使用 SynchronizationContext 对象。我已经包含了示例代码。基本上,您要做的就是将线程任务包装在一个类中,该类可以保存对主线程提供的同步上下文对象和回调的引用,然后在工作结束后调用这些对象。

这是一个简单的形式:

public partial class Form1 : Form
{
    private SynchronizationContext _synchronizationContext;

    public Form1()
    {
        InitializeComponent();
        //Client must be careful to create sync context soimehwere they are sure to be on main thread
        _synchronizationContext = AsyncOperationManager.SynchronizationContext;
    }

    //Callback method implementation - must be of this form
    public void ReceiveThreadData(object threadData)
    {
        // Can use directly in UI without error
        this.listBoxMain.Items.Add((string)threadData);
    }

    private void DoSomeThreadWork()
    {
        // Thread needs callback and sync context.  
        // You probably want to derive your own callback from the NET SendOrPostCallback class.
        SendOrPostCallback callback = new SendOrPostCallback(ReceiveThreadData);
        SomeThreadTask task = new SomeThreadTask(_synchronizationContext, callback);
        Thread thread = new Thread(task.ExecuteThreadTask);
        thread.Start();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DoSomeThreadWork();
    }

}

这是一个具有线程任务的类

/// SomeThreadTask defines the work a thread needs to do and also provides any data required along with callback pointers etc.
/// Populate a new SomeThreadTask instance with a synch context and callnbackl along with any data the thread needs
/// then start the thread to execute the task.
/// </summary>
public class SomeThreadTask
{

    private string _taskId;
    private SendOrPostCallback _completedCallback;
    private SynchronizationContext _synchronizationContext;

    /// <summary>
    /// Get instance of a delegate used to notify the main thread when done.
    /// </summary>
    internal SendOrPostCallback CompletedCallback
    {
        get { return _completedCallback; }
    }

    /// <summary>
    /// Get SynchronizationContext for main thread.
    /// </summary>
    internal SynchronizationContext SynchronizationContext
    {
        get { return _synchronizationContext; }
    }

    /// <summary>
    /// Thread entry point function.
    /// </summary>
    public void ExecuteThreadTask()
    {

        //Just sleep instead of doing any real work
        Thread.Sleep(5000);

        string message = "This is some spoof data from thread work.";

        // Execute callback on synch context to tell main thread this task is done.
        SynchronizationContext.Post(CompletedCallback, (object)message);


    }

    public SomeThreadTask(SynchronizationContext synchronizationContext, SendOrPostCallback callback)
    {
        _synchronizationContext = synchronizationContext;
        _completedCallback = callback;
    }

}

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:

public partial class Form1 : Form
{
    private SynchronizationContext _synchronizationContext;

    public Form1()
    {
        InitializeComponent();
        //Client must be careful to create sync context soimehwere they are sure to be on main thread
        _synchronizationContext = AsyncOperationManager.SynchronizationContext;
    }

    //Callback method implementation - must be of this form
    public void ReceiveThreadData(object threadData)
    {
        // Can use directly in UI without error
        this.listBoxMain.Items.Add((string)threadData);
    }

    private void DoSomeThreadWork()
    {
        // Thread needs callback and sync context.  
        // You probably want to derive your own callback from the NET SendOrPostCallback class.
        SendOrPostCallback callback = new SendOrPostCallback(ReceiveThreadData);
        SomeThreadTask task = new SomeThreadTask(_synchronizationContext, callback);
        Thread thread = new Thread(task.ExecuteThreadTask);
        thread.Start();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DoSomeThreadWork();
    }

}

This is a class that has the thread task

/// SomeThreadTask defines the work a thread needs to do and also provides any data required along with callback pointers etc.
/// Populate a new SomeThreadTask instance with a synch context and callnbackl along with any data the thread needs
/// then start the thread to execute the task.
/// </summary>
public class SomeThreadTask
{

    private string _taskId;
    private SendOrPostCallback _completedCallback;
    private SynchronizationContext _synchronizationContext;

    /// <summary>
    /// Get instance of a delegate used to notify the main thread when done.
    /// </summary>
    internal SendOrPostCallback CompletedCallback
    {
        get { return _completedCallback; }
    }

    /// <summary>
    /// Get SynchronizationContext for main thread.
    /// </summary>
    internal SynchronizationContext SynchronizationContext
    {
        get { return _synchronizationContext; }
    }

    /// <summary>
    /// Thread entry point function.
    /// </summary>
    public void ExecuteThreadTask()
    {

        //Just sleep instead of doing any real work
        Thread.Sleep(5000);

        string message = "This is some spoof data from thread work.";

        // Execute callback on synch context to tell main thread this task is done.
        SynchronizationContext.Post(CompletedCallback, (object)message);


    }

    public SomeThreadTask(SynchronizationContext synchronizationContext, SendOrPostCallback callback)
    {
        _synchronizationContext = synchronizationContext;
        _completedCallback = callback;
    }

}
梦中楼上月下 2024-11-14 10:22:04

您可以从 UI 线程保存对 SynchronizationContext.Current 的引用,然后调用其 PostSend 方法在 UI 线程上运行代码。

You can save a reference to SynchronizationContext.Current from the UI thread, then call its Post or Send methods to run code on the UI thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文