How do I communicate between C # child threads and the main thread
First of all, I recently encountered a problem, that is, when writing a message queue, found that the message queue each time to receive a message is created a new thread. This results in the message processing is not carried out on the main thread, but some of the steps are to be through the main thread to operate. This leads to a child thread how to inform the main thread to do what things.
in order to solve the above problems I found a good many information, many are commissioned to solve, and then I saw my project through this begininvoker solution is not very easy to use. Does not solve the current problem, at this time I found the SynchronizationContext object. The use of this image is to record the context of a thread and then after the child thread processing, to use the main process to operate when you can go to post or send an event to resolve, this is very convenient, the code is as follows:
Class TestClient
{
private Thread workthread;
Private SynchronizationContext Mainthreadsyncontext;
The public testclient ()//constructor is, of course, the {Mainthreadsyncontext = synchronizationcontext.current that the main thread executes
;//Where the main thread's context is recorded
workthread = new Thread (ThreadStart (DoWork));
private void Onconnected (object state)//Because it is a post call to the main thread's synchronization object, this is performed in the main thread {//
Here it's back to the main thread.
//do something
}
private void DoWork ()//This is Workthread thread execution
{
//here do something (connect ...).
//This is done
mainthreadsyncontext.post (new SendOrPostCallback (onconnected), null);//Notification main thread
}
}
I hereby record the above code to facilitate my own future viewing and hope to be able to help people with whom I meet the same problem.
-The more you know, the more you don't know, and learn a lot.