C # Multithreaded Tutorials (C # learning Diary 2017-10-16)

Source: Internet
Author: User
Tags thread class

Reprint Address: Click on the Open link


(1) Do not need to pass parameters, and do not need to return parameters

ThreadStart is a delegate, which is defined as void ThreadStart (), with no parameters and return values.

Class program
{
static void Main (string[] args)
{for
(int i = 0; i < i++)
{
ThreadStart th Readstart = new ThreadStart (Calculate);
Thread thread = new Thread (ThreadStart);
Thread. Start ();
}
Thread.Sleep ();
Console.read ();
}
public static void Calculate ()
{
DateTime = datetime.now;//Gets the current time
Random ra = new Random ();//Random Number Object C16/>thread.sleep (RA. Next (10,100));//randomly dormant 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 argument but no return value.

Class program
{
static void Main (string[] args)
{for
(int i = 0; i < i++)
{
Parameterizedt Hreadstart Tstart = new Parameterizedthreadstart (Calculate);
Thread thread = new Thread (tstart);
Thread. Start (i*10+10);//pass parameter
}
thread.sleep;
Console.read ();
}
public static void Calculate (object arg)
{
Random ra = new Random ();//Random Number Object
thread.sleep (RA. Next (10, 100));//randomly dormant for a period of time
Console.WriteLine (ARG);
}


(3) Use of specialized thread classes (commonly used)

Using a thread class can have multiple parameters and multiple return values, very flexible.

Class program
{
static void Main (string[] args)
{
mythread mt = new Mythread (MB);
ThreadStart ThreadStart = new ThreadStart (Mt. Calculate);
Thread thread = new Thread (ThreadStart);
Thread. Start ();
   Waits for thread to end while (thread)
. ThreadState!= threadstate.stopped)
{
thread.sleep;
}
Console.WriteLine (Mt. result);//Print return value
console.read ();
}
}
public class mythread//Thread class
{public
int parame {set; get;} Parameter public
int result {set; 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));//randomly dormant for a period of time
Console.WriteLine (this. Parame);
This. result = this. Parame * ra. Next (in);
}



(4) Using anonymous methods (commonly used)

Starting a thread with an anonymous method can have multiple parameters and return values, and is 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));//randomly dormant 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 anonymous method
//waits for thread to end while (thread)
. ThreadState!= threadstate.stopped)
{
thread.sleep;
}
Console.WriteLine (result);//Print return value
console.read ();
}




(5) using the delegate to open multithreading (multithreading depth)

1, using the BeginInvoke and EndInvoke method of the delegate (Delegate) to manipulate the thread

The BeginInvoke method can use a thread to asynchronously execute the method that the delegate points to. The return value of the method is then obtained by means of the EndInvoke method (the return value of the EndInvoke method is the return value of the invoked method), or the method is determined to have been successfully invoked.

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);
The EndInvoke method will be blocked for 2 seconds
int result = task. EndInvoke (asyncresult);
Console.WriteLine (result);
Console.read ();
}


2, using the IAsyncResult.IsCompleted property to determine whether the asynchronous call is complete


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 while
(!asyncresult.iscompleted)
{
Console.Write ("*");
Thread.Sleep (MB);
Because the asynchronous call is complete, EndInvoke immediately returns the result
int results = task. EndInvoke (asyncresult);
Console.WriteLine (result);
Console.read ();
}


3. Use the WaitOne method to wait for the asynchronous method execution to complete

The first parameter of the WaitOne represents the number of milliseconds to wait, and the WaitOne method waits for the specified time until the asynchronous call completes and notifies the WaitOne method to return True. When a specified time is waiting, the asynchronous call is not completed, and the WaitOne method returns False, and if the specified time is 0, it does not wait, and if-1, it means to wait forever until the asynchronous call completes.


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 while
(!asyncresult.asyncwaithandle.waitone (false))
{
Console.Write ("*");
}
int result = task. EndInvoke (asyncresult);
Console.WriteLine (result);
Console.read ();
}


4, use callback method to return the result

Be aware of the "my. BeginInvoke (3,300, methodcompleted, my) ", BeginInvoke method of parameter passing way:

The previous part (3,300) is the parameter of its delegate itself.

The penultimate argument (methodcompleted) is the callback method delegate type, which is a delegate to the callback method, has no return value, has a IAsyncResult type of argument, and when the method is executed, The system automatically invokes the Methodcompleted method.

The last parameter (my) needs to pass some values to the Methodcompleted method, which can generally pass the delegate of the invoked method, which can be obtained using the IAsyncResult.AsyncState property.


Class program
{
private delegate int MyMethod (int second, int millisecond);
Thread execution methods
private static int method (int second, int millisecond)
{
Console.WriteLine ("Thread Hibernate" + (second * 1000 + Millisecond) + "millisecond");
Thread.Sleep (Second * 1000 + 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 completed, Results:" + result);
}
static void Main (string[] args)
{
MyMethod i = method;
IAsyncResult asyncresult = My. BeginInvoke (3,300, methodcompleted, my);
Console.WriteLine ("Task Start");
Console.read ();
}


5, other components of the beginxxx and EndXxx methods

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. The methods used are 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 ();
}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.