Search code examples
.net-3.5c#-3.0compact-frameworkthread-safetyclass-library

How to safe data from another thread to use on controls?


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.


Solution

  • 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.