In many cases, you can [always] or [need] use multiple threads. This will bring a better user experience, so that you will not suddenly get stuck when you are operating a function. In the case of. net winform, you can consider using the [asynchronous/auxiliary thread] when the control operations are not involved and the data volume is large 〕.
The asynchronous/multithreading method generally considers the creation of the delegate, and then BeginInvoke, or directly implements the Thread operation. In fact, asynchronous and multithreading are slightly different, more Strict Asynchronization seems to have something to do with the structure of what hard disk, rather than multithreading. No matter how many profound things are, the following uses delegation and Thread as examples of several creation methods and auxiliary Thread security issues.
Asynchronous
(1) create a delegate. ② Create a delegated instance or an event. ③ Bind the event method. ④ Call
Public delegate void ThreadHandler ();
Public ThreadHandler ThreadEvent = null;
Public void ThreadInvoke ()
{
//...
Return;
}
Then, call it in a specific event as follows:
ThreadEvent = new ThreadHandler (ThreadInvoke );
ThreadEvent. BeginInvoke (result => // callback function. When ThreadInvoke finishes the call, it ends asynchronous.
{
(Result. AsyncState as ThreadHandler). EndInvoke (result );
}, Null );
Multithreading
With the help of the above Code, common examples include:
Thread t = new Thread (ThreadInvoke); // Common Mode
T. IsBackground = true;
T. Start ();
Or use the anonymous method that appears in framework 2.0:
Thread t1 = new Thread (delegate () // anonymous method
{
This. Invoke (new Action (delegate () // here this is the form of the main thread UI
{
//... Call the operations of the main thread UI control
}));
});
T1.IsBackground = true;
T1.Start ();
Or use lambda expressions more directly:
Thread t2 = new Thread () => // lambda expression
{
// Auxiliary thread execution... you can view the threadId and ui thread are different.
});
T2.IsBackground = true;
T2.Start ();
Thread Security
Generally, multithreading involves thread security. thread security generally calls controls in non-main threads. Therefore, it is generally used to call controls (or assign values) in auxiliary threads) then delegate the main thread method to reference the control. The code can generally be written in the auxiliary thread as follows:
{
This. Invoke (new Action (delegate () // here this is the form of the main thread UI
{
//... Call the operations of the main thread UI control
}));
});