Preface:
Multi-thread development of winform forms, with specific writing methods.
In a thread other than the winform form thread, controlling the objects on the winform will cause an error.
There are many writing methods available on the network, allowing multithreading to control winform objects across threads.
This chapter uses an anonymous function to implement this function to provide different options.
For thread-related data, refer to-[object-oriented]: Thread
Sample Form:
Button1: button
Textbox1: textbox
Sample program:
Private void button1_click (Object sender, eventargs e) {// record winform synccontext synchronizationcontext synccontext = synchronizationcontext. current; // create the work to be executed by multiple threads waitcallback threadprocdelegate = delegate (object state) {sendorpostcallback syncdelegate = NULL; // control the form-Notification start syncdelegate = delegate (Object stateex) {MessageBox. show ("starts with Multiple Threads"); this. textbox1.text = "multi-thread start" ;}; synccontext. send (SY Ncdelegate, null); // call syncdelegate to complete the execution. // Execute work-sleep for 5 seconds thread. sleep (5000); // control the form-Notification end syncdelegate = delegate (Object stateex) {MessageBox. show ("multi-thread end"); this. textbox1.text = "multi-thread end" ;}; synccontext. post (syncdelegate, null); // call syncdelegate. After the call is complete, execute the following command. }; Threadpool. queueuserworkitem (threadprocdelegate, null );}
The package of threadprocdelegate indicates the work to be executed by multiple threads.
Syncdelegate indicates that multiple threads need to control the work of the form.
Note:
There are many background technologies referenced in this article, but the content of this article only retains the actual work.
If you are interested in in-depth research, you can refer to the following data:
1. Anonymous functions: http://msdn.microsoft.com/zh-tw/library/bb882516.aspx
The anonymous form is used to wrap the form into a delegate. For details, refer to the msdn document in the link.
This article mainly uses the [outer variable of the anonymous method] to simplify the transfer of objects in different threads.
2. synchronizationcontext: http://msdn.microsoft.com/zh-tw/library/system.threading.synchronizationcontext (vs.90). aspx
Synchronizationcontext is mainly used to process synchronization jobs. The Core Thread is encapsulated for multi-thread synchronization.
Windowsformssynchronizationcontext is the winform version of synchronizationcontext.
3. asynchronous programming mode: http://msdn.microsoft.com/zh-tw/library/ms228969.aspx
Microsoft's asynchronous design model, from 2.0 to 4.0, is almost undergoing significant evolution.
We strongly recommend that you be interested in asynchronous programming and read the entire article.