Bring data came from async operation to main thread

我与影子孤独终老i 提交于 2020-01-25 08:43:06

问题


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.

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.

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


回答1:


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.

EDIT 1

As an example:

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);
}

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.



来源:https://stackoverflow.com/questions/1846832/bring-data-came-from-async-operation-to-main-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!