views:

55

answers:

1

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  A: 

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.

ctacke
Deleted previous comment, my bad...this looks like working..Thanx...i will fully apply it now.
Can you make an example of how would you invoke if you had a custom object and make it safe your way with control. Cause i could only succeeded to make it work but i now need to invoke with an Action and pass the event raising.
This is horrible as if the library is created on a background thread it will stop working. However, this is exactly what I do in some of my libs (where it hangs if we call SetSystemPowerState to suspend if not on the main thread) so..... it's probably the best solution. :(
Quibblesome
if it were created on a background thread, the consumer will get a "method must be called with Invoke" exception (with CF 2.0 and later anyway). True, there's no guaranteed way to make this work in all cases.
ctacke
The library is not created in a background thread, Async TCP operations bringing and sending data though goes in Processor Multi I/O and this by default of course creates another thread. Thanx ctacke i will try soon as possible...

related questions