This article was reproduced from: http://www.jb51.net/article/46234.htm
This article mainly introduces the use of multithreading in C # several ways, through the example Learning C # multithreading use, We refer to the use of it
(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.
Copy CodeThe code is as Follows:
Class Program
{
static void Main (string[] Args)
{
for (int i = 0; I <; i++)
{
ThreadStart ThreadStart = new ThreadStart (Calculate);
Thread thread = new Thread (threadstart);
Thread. Start ();
}
Thread.Sleep (2000);
Console.read ();
}
public static void Calculate ()
{
DateTime time = Datetime.now;//get current times
Random RA = new random ();//stochastic Number Object
Thread.Sleep (ra. Next (10,100));//random sleep for a period of time
Console.WriteLine (time. 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.
Copy CodeThe code is as Follows:
Class Program
{
static void Main (string[] Args)
{
for (int i = 0; I <; i++)
{
Parameterizedthreadstart Tstart = new Parameterizedthreadstart (Calculate);
Thread thread = new Thread (tstart);
Thread. Start (i*10+10);//pass Parameters
}
Thread.Sleep (2000);
Console.read ();
}
public static void Calculate (object Arg)
{
Random RA = new random ();//stochastic 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!
Copy CodeThe code is as Follows:
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 thread to end
While (thread. threadstate! = Threadstate.stopped)
{
Thread.Sleep (10);
}
Console.WriteLine (mt. Result);//print return value
Console.read ();
}
}
public class Mythread//threading Class
{
public int Parame {set; get;} Parameters
public int Result {set; get;} return value
constructor function
Public MyThread (int Parame)
{
This. Parame = Parame;
}
Thread Execution methods
public void Calculate ()
{
Random RA = new random ();//stochastic 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!
Copy CodeThe code is as Follows:
Class Program
{
static void Main (string[] Args)
{
int Parame = 100;//as parameter
int Result = 0;//as return value
Anonymous methods
ThreadStart ThreadStart = new ThreadStart (delegate ()
{
Random RA = new random ();//stochastic 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 Start anonymous method
Wait for 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.
Copy CodeThe code is as Follows:
Class Program
{
Private delegate int newtaskdelegate (int ms);
private static int NewTask (int Ms)
{
Console.WriteLine ("task start");
Thread.Sleep (ms);
Random random = new Random ();
int n = random. Next (10000);
Console.WriteLine ("mission accomplished");
Return n;
}
static void Main (string[] Args)
{
Newtaskdelegate task = newtask;
IAsyncResult AsyncResult = Task. BeginInvoke (+, null, null);
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
Copy CodeThe code is as Follows:
Class Program
{
Private delegate int newtaskdelegate (int ms);
private static int NewTask (int Ms)
{
Console.WriteLine ("task start");
Thread.Sleep (ms);
Random random = new Random ();
int n = random. Next (10000);
Console.WriteLine ("mission accomplished");
Return n;
}
static void Main (string[] Args)
{
Newtaskdelegate task = newtask;
IAsyncResult AsyncResult = Task. BeginInvoke (+, null, null);
Wait for asynchronous execution to complete
While (!asyncresult.iscompleted)
{
Console.Write ("*");
Thread.Sleep (100);
}
Because the asynchronous call is complete, EndInvoke returns the result immediately
int result = Task. 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.
Copy CodeThe code is as Follows:
Class Program
{
Private delegate int newtaskdelegate (int ms);
private static int NewTask (int Ms)
{
Console.WriteLine ("task start");
Thread.Sleep (ms);
Random random = new Random ();
int n = random. Next (10000);
Console.WriteLine ("mission accomplished");
Return n;
}
static void Main (string[] Args)
{
Newtaskdelegate task = newtask;
IAsyncResult AsyncResult = Task. BeginInvoke (+, null, null);
Wait 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.
Copy CodeThe code is as Follows:
Class Program
{
Private delegate int MyMethod (int second, int millisecond);
Thread Execution methods
private static int method (int second, int Millisecond)
{
Console.WriteLine ("thread hibernation" + (second * + Millisecond) + "ms");
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:
Copy CodeThe code is as Follows:
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 ();
}
}
Examples of several ways to use multithreading in C #