将数据从异步操作来到主线程 [英] Bring data came from async operation to main thread

查看:145
本文介绍了将数据从异步操作来到主线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个问题我有,我从对发送和接收数据的一些异步操作的库接收数据。虽然我在移动Windows窗体或桌面接收数据和获取数据我需要处理跨线程操作。我处理这个,同时检查InvokeRequired和做动作,如果真的......等等......但是,我真的希望是让这个消失,正确地得到我的数据,我就可以将它们绑定操作等,没有处理这种跨线程问题。

This is a "problem" i have with data that i receive from a library that has some Async operations on sending and receiving data. While i receive data and get data in my Mobile Windows Form or Desktop i need to deal with the cross thread operation. I deal with this while checking InvokeRequired and do Action if true...etc...But, what i really would like is to make this disappear and get my data correctly so i could bind them manipulate etc, without handling this cross-thread problem.

问题是:如何处理数据到我的库中,然后引发该事件的客户端?在那里他们可以为所欲为,而不处理跨线程处理。

Question is: How can i manipulate data into my library and then raise the event to the client? Where they could whatever they want without deal cross thread handling.

这必须是有效的精简框架也导致客户端是移动客户端。这就是为什么一个解决方案使用ISynchronizeInvoke无效找到。

This must be valid for Compact Framework too cause clients are Mobile Clients. And that's why a solution found using ISynchronizeInvoke is not valid.

任何帮助,使pciated这个漂亮的AP $ P $!先谢谢了。

Any help to make this nice appreciated! Thanks in advance.

推荐答案

您可以创建在库的构造控制按钮,然后用它调用并引发该事件的之后的的调用。那么消费者将获得在创建你的库类线程的上下文事件。如果你让一个组件,它是最有可能的,这将在UI线程上创建的,因此您的活动将在UI线程提高。

You could create a COntrol in the constructor of your Library, then Invoke with it and raise the event after the invoke. The consumer would then get the event in the context of the thread that created your library class. If you make it a Component, it's most likely that it will be created on the UI thread, and therefore your events will raise in the UI thread.

修改1

作为一个例子:

private Control m_invoker = new Control();
public event EventHandler MyEvent;

private void RaiseMyEvent(object o, EventArgs args)
{
    EventHandler handler = MyEvent;
    if (handler == null) return;

    if (m_invoker.InvokeRequired)
    {
        m_invoker.BeginInvoke(new EventHandler(RaiseMyEvent), 
                              new object[] { o, args });
        return;
    }

    handler(o, args);
}

所以你的code称之为RaiseMyEvent,这反过来迁移调用该创建当前对象的线程,然后提出了实际的事件。

So your code would call RaiseMyEvent, which in turns migrates the call to the thread that create the current object and then raises the actual event.

这篇关于将数据从异步操作来到主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆