In fact, this is also a question asked during the interview: (I am here to commemorate it. Note: It is just a simple list. For detailed principles and analysis, see the relevant chapter of the third edition of CLR via C) 1. Use the thread pool to initiate asynchronous operations
Using system; using system. threading; namespace asynchronous {class program {static void main (string [] ARGs) {console. writeline ("main thread: Prepare to initiate a series of asynchronous operations... "); threadpool. queueuserworkitem (computeboundop, 5); threadpool. queueuserworkitem (computeboundop, 7); console. writeline ("main thread: do other things... "); thread. sleep (1, 1000); console. writeline ("press enter to exit... "); console. readline ();} Private Static void computeboundop (Object O) {console. writeline ("Asynchronous Operation callback: State = {0}", O); thread. sleep (1000 );}}}
Result: or 2. Use the task in threading. Tasks.
Using system; using system. threading; using system. threading. tasks; namespace asynchronous {class program {static void main (string [] ARGs) {console. writeline ("main thread: Prepare to initiate a series of asynchronous operations... "); task T = new task (computeboundop, 5); T. start (); console. writeline ("main thread: do other things... "); thread. sleep (1, 1000); console. writeline ("press enter to exit... "); console. readline ();} Private Static void computeboundop (Object O) {console. writeline ("Asynchronous Operation callback: State = {0}", O); thread. sleep (1000 );}}}
3. Use System. Threading. Timer
Using system; using system. threading; namespace asynchronous {class program {static void main (string [] ARGs) {console. writeline ("main thread: Prepare to initiate a series of asynchronous operations... "); timer T = new timer (computeboundop, 5, 50, 0); console. writeline ("main thread: do other things... "); thread. sleep (1, 1000); console. writeline ("press enter to exit... "); console. readline ();} Private Static void computeboundop (Object O) {console. writeline ("Asynchronous Operation callback: State = {0}", O); thread. sleep (1000 );}}}
4. Use the beginxxx method in APM (asynchronous programming model)
Using system; using system. threading; namespace asynchronous {class program {delegate void mydelegate (Object O); static void main (string [] ARGs) {console. writeline ("main thread: Prepare to initiate a series of asynchronous operations... "); mydelegate = computeboundop; mydelegate. begininvoke (null, computeboundopcallback, 5); console. writeline ("main thread: do other things... "); thread. sleep (1, 5000); console. writeline ("press enter to exit... "); console. readline ();} Private Static void computeboundop (Object O) {thread. sleep (1000); // simulate asynchronous operations in some time-consuming operations} Private Static void computeboundopcallback (iasyncresult AR) {console. writeline ("Asynchronous Operation callback: {0}", ar. asyncstate );}}}
To be continued...