(1) Do not need to pass parameters, and do not need to return parameters
ThreadStart is a delegate, and the delegate is defined as void ThreadStart (), with no parameters and a return value.
Class program{static void Main (string[] args) {for (int i = 0; i <; i++) {ThreadStart ThreadStart = new ThreadStart (Ca Lculate); Thread thread = new Thread (threadstart); thread. Start ();} Thread.Sleep (2000); Console.read ();} public static void Calculate () {DateTime = datetime.now;//Gets the current time of the random RA = new Random ();//Random Number Object Thread.Sleep (RA. Next (10,100));//random sleep for a period of time Console.WriteLine. Minute + ":" + Time.millisecond);}}
(2) need to pass a single parameter
The Parameterthreadstart delegate is defined as void Parameterizedthreadstart (object state), with one parameter but no return value.
Class program{static void Main (string[] args) {for (int i = 0; i <; i++) {Parameterizedthreadstart Tstart = new Parame Terizedthreadstart (Calculate); Thread thread = new Thread (tstart); thread. Start (i*10+10);//Pass Parameter}thread.sleep (2000); Console.read ();} public static void Calculate (object arg) {Random RA = new Random ();//Random Number Object Thread.Sleep (RA. Next (10, 100));//random sleep for a period of time Console.WriteLine (ARG);}}
(3) Use specialized threading classes (common)
Using a thread class can have multiple parameters with multiple return values, which is very flexible!
Class program{static void Main (string[] args) {MyThread mt = new MyThread (100); ThreadStart ThreadStart = new ThreadStart (Mt. Calculate); Thread thread = new Thread (threadstart); thread. Start (); Wait for the thread to end while (thread. ThreadState! = threadstate.stopped) {thread.sleep (10);} Console.WriteLine (Mt. Result);//Print return value Console.read ();}} public class mythread//thread class {public int Parame {set; get;} Parameter public int Result {set; get;} return value//constructor public MyThread (int parame) {this. Parame = Parame;} Thread execution method public void Calculate () {Random RA = new Random ();//Random Number Object Thread.Sleep (RA. Next (10, 100));//random sleep for a period of time Console.WriteLine (this. Parame); this. Result = this. Parame * ra. Next (10, 100);}}
(4) Using anonymous methods (common)
Using an anonymous method to start a thread can have multiple parameters and return values, and is very convenient to use!
Class program{static void Main (string[] args) {int Parame = 100;//as parameter int Result = 0;//as return value//anonymous method ThreadStart ThreadStart = New ThreadStart (delegate () {Random RA = new Random ();//Random Number Object Thread.Sleep (RA. Next (10, 100));//random sleep for a period of time Console.WriteLine (Parame);//output parameter result = Parame * ra. Next (10, 100);//Calculate return value}); Thread thread = new Thread (threadstart); thread. Start ();//Multithreading initiates an anonymous method//waits for the thread to end while (thread. ThreadState! = threadstate.stopped) {thread.sleep (10);} Console.WriteLine (Result);//Print return value Console.read ();}}
(5) using a delegate to turn on multithreading (multithreading in depth)
1. Use the BeginInvoke and EndInvoke methods of the delegate (Delegate) to manipulate threads
The BeginInvoke method can use threads to asynchronously execute the method that the delegate points to. The return value of the method is then obtained by the EndInvoke method (the return value of the EndInvoke method is the return value of the called method), or the method has been successfully called.
Class Program{private delegate int newtaskdelegate (int ms);p rivate static int newtask (int ms) {Console.WriteLine ("Task Start") ; Thread.Sleep (MS); Random random = new random (); int n = random. Next (10000); Console.WriteLine ("Task Complete"); return n;} static void Main (string[] args) {newtaskdelegate task = Newtask;iasyncresult AsyncResult = task. BeginInvoke (n, null, NULL); The//endinvoke method will be blocked for 2 seconds int result = task. EndInvoke (AsyncResult); Console.WriteLine (result); Console.read ();}}
2. Use the IAsyncResult.IsCompleted property to determine whether an asynchronous call is complete
Class Program{private delegate int newtaskdelegate (int ms);p rivate static int newtask (int ms) {Console.WriteLine ("Task Start") ; Thread.Sleep (MS); Random random = new random (); int n = random. Next (10000); Console.WriteLine ("Task Complete"); return n;} static void Main (string[] args) {newtaskdelegate task = Newtask;iasyncresult AsyncResult = task. BeginInvoke (n, NULL, NULL),//waits for asynchronous execution to complete while (!asyncresult.iscompleted) {Console.Write ("*"); Thread.Sleep (100);} Because the asynchronous call has been completed, EndInvoke returns the result, int result = task, immediately. EndInvoke (AsyncResult); Console.WriteLine (result); Console.read ();}}
3. Use the WaitOne method to wait for asynchronous method execution to complete
The first parameter of WaitOne represents the number of milliseconds to wait, and within a specified time, the WaitOne method waits until the asynchronous call is complete and notifies the WaitOne method to return True. When the asynchronous call is still not completed after waiting for the specified time, the WaitOne method returns False if the specified time is 0, indicating that no wait, if 1, means that the asynchronous call is completed forever.
Class Program{private delegate int newtaskdelegate (int ms);p rivate static int newtask (int ms) {Console.WriteLine ("Task Start") ; Thread.Sleep (MS); Random random = new random (); int n = random. Next (10000); Console.WriteLine ("Task Complete"); return n;} static void Main (string[] args) {newtaskdelegate task = Newtask;iasyncresult AsyncResult = task. BeginInvoke (n, NULL, NULL),//waits for asynchronous execution to complete while (!asyncresult.asyncwaithandle.waitone (), false) {Console.Write ("*") );} int result = task. EndInvoke (AsyncResult); Console.WriteLine (result); Console.read ();}}
4. Return results Using callback method
Be aware of "my." BeginInvoke (3,300, methodcompleted, my) ", BeginInvoke method parameter passing:
The previous section (3,300) is the parameter of its delegate itself.
The second-to-last argument (methodcompleted) is the callback method delegate type, which is the delegate of the callback method, this delegate has no return value, has a parameter of type IAsyncResult, and when the method is executed, The Methodcompleted method is called automatically by the system.
The last parameter (my) needs to pass some values to the Methodcompleted method, which can generally pass the delegate of the called method, which can be obtained using the IAsyncResult.AsyncState property.
Class Program{private delegate int MyMethod (int second, int millisecond);//thread execution method private static int method (int second, int Millisecond) {Console.WriteLine ("Thread Hibernation" + (second * + millisecond) + "milliseconds"); Thread.Sleep (second * + millisecond); Random random = new random (); return random. Next (10000);} callback method private static void methodcompleted (IAsyncResult asyncResult) {if (AsyncResult = = NULL | | asyncresult.asyncstate = = NULL) {Console.WriteLine ("Callback Failed!!! "); return;} int result = (asyncresult.asyncstate as MyMethod). EndInvoke (AsyncResult); Console.WriteLine ("Task accomplished, Result:" + result);} static void Main (string[] args) {MyMethod my = Method;iasyncresult AsyncResult = My. BeginInvoke (3,300, methodcompleted, my); Console.WriteLine ("Task Start"); Console.read ();}}
5. BeginXxx and EndXxx methods for other components
There are also methods similar to BeginInvoke and EndInvoke in other. Net components, such as the BeginGetResponse and EndGetResponse methods of the System.Net.HttpWebRequest class. It is used similar to the BeginInvoke and EndInvoke methods of the delegate type, for example:
Class program{//callback function private static void requestcompleted (IAsyncResult asyncResult) {if (AsyncResult = = NULL | | Asyncresult.asyncstate==null) {Console.WriteLine ("Callback Failed"); return;} HttpWebRequest HWR = asyncresult.asyncstate as HttpWebRequest; HttpWebResponse response = (HttpWebResponse) hwr. EndGetResponse (AsyncResult); StreamReader sr = new StreamReader (response. GetResponseStream ()); string str = Sr. ReadToEnd (); Console.WriteLine ("Return stream length:" +str. Length);} static void Main (string[] args) {HttpWebRequest request = (HttpWebRequest) webrequest.create ("http://www.baidu.com"); /Asynchronous request IAsyncResult AsyncResult = Request. BeginGetResponse (requestcompleted, request); Console.WriteLine ("Task Start"); Console.read ();}}