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-T开发者_如何学运维hread 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.
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;
}
}
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.
精彩评论