C # six major threading operations

Source: Internet
Author: User

C # Threading Operations common six ways to operate 2009-08-28 15:25 Nokiaguy Blog Parkfont Size:T | T

What is the specific way to do C # threading? What are the characteristics and main applications of the C # threading method? So this article will introduce you to this aspect of the content.

AD:2014WOT Global Software Technology Summit Beijing Station course video release

What are common ways to do C # threading operations? What is the implementation of the C # threading method? So let's take a look at what the six methods of specific C # threading operations are, and what are their characteristics?

C # thread operations one, BeginInvoke and EndInvoke methods with delegates (Delegate) to manipulate threads

There are many ways to use threading in C #, and the BeginInvoke and EndInvoke methods of using delegates are one of them. 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. There are four ways to get the return value from the EndInvoke method.

C # Thread Operations Ii. Use the EndInvoke method directly to get the return value

When using BeginInvoke to invoke a method asynchronously, the EndInvoke method will block until the method is executed if the method is not finished. As shown in the following code:

  1. Using System;
  2. Using System.Collections.Generic;
  3. Using System.Linq;
  4. Using System.Text;
  5. Using System.Threading;
  6. Namespace MyThread
  7. {
  8. Class Program
  9. {
  10. Private static int NewTask (int ms)
  11. {
  12. Console.WriteLine ("task Start");
  13. Thread.Sleep (MS);
  14. Random random = new Random ();
  15. int n = random. Next (10000);
  16. Console.WriteLine ("Mission Accomplished");
  17. return n;
  18. }
  19. Private Delegate int newtaskdelegate (int ms);
  20. static void Main (string[] args)
  21. {
  22. Newtaskdelegate task = NewTask;
  23. IAsyncResult AsyncResult = task.  BeginInvoke (+, null, null);
  24. EndInvoke method will be blocked for 2 seconds
  25. int result = task. EndInvoke (AsyncResult);
  26. Console.WriteLine (result);
  27. }
  28. }
  29. }

After running the above program, the program does not output the final result (a random integer) until 2 seconds since the NewTask method is delayed by sleep by 2 seconds. If you do not call the EndInvoke method, the program exits immediately, because the thread created with BeginInvoke is a background thread, and once all of the foreground threads have exited (where the main thread is a foreground thread), the thread will end regardless of whether the background thread finishes executing. and exit the program. Detailed information about the foreground and background threads will be explained in a later section.

Readers can use the above procedure to do the following experiments. First, add the following code to the beginning of the Main method:

    1. Thread.Sleep (10000);

To delay the main method for 10 seconds, execute the following code, then press CTRL+F5 to run the program, open Enterprise Manager, observe the number of threads in the current program, assume that the number of threads is 4, and after 10 seconds, the number of threads increases to 5. This is because when the BeginInvoke method is called, a thread is created to execute the NewTask method asynchronously, so the threads increase by one.

C # Threading Operations third, use the IAsyncResult AsyncResult property to determine whether an asynchronous call is complete

Although the method above can implement asynchronous invocation well, when calling the EndInvoke method to get the result of the call, the whole program is just as dead, so the user doesn't feel too good, so we can use asyncresult to determine whether the asynchronous call is complete and display some hints. Doing so can increase the user experience. The code is as follows:

  1. static void Main (string[] args)
  2. {
  3. Newtaskdelegate task = NewTask;
  4. IAsyncResult AsyncResult =
  5. Task.  BeginInvoke (+, null, null);
  6. while (!asyncresult.iscompleted)
  7. {
  8. Console.Write ("*");
  9. Thread.Sleep (100);
  10. }
  11. Because the asynchronous call is complete, EndInvoke returns the result immediately
  12. int result = task. EndInvoke (AsyncResult);
  13. Console.WriteLine (result);
  14. }

The result of the above code is as shown.

Because it is asynchronous, "*" may be output before "task start", as shown in.

C # Threading Operations Iv. using the WaitOne method to wait for asynchronous method execution to complete

Using the WaitOne method is another way to determine whether an asynchronous call is complete. The code is as follows:

    1. static void main (string[] args)  
    2. newtaskdelegate task = newtask;  
    3. iasyncresult asyncresult = task. BeginInvoke (2000, null, null);  
    4. Li class= "alt" > 
    5. while  (!asyncresult.asyncwaithandle.waitone (100,  false))  
    6.  console.write (
    7.  
    8.  
    9. int& Nbsp;result = task. EndInvoke (AsyncResult);  
    10. Console.WriteLine (result);  
    11. }  

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.

C # Threading Operations v. Returning results using callback methods

The methods described above are actually only equivalent to one method. Although these methods can successfully return the results, but also to give the user some hints, but in this process, the whole program is like dead (if the reader in the GUI program is very obvious to use these methods), in order to call the process, the program can still do other work, you must use the way of asynchronous calls. Below we use GUI program to write an example, the code is as follows:

  1. Private Delegate int MyMethod ();
  2. Private int method ()
  3. {
  4. Thread.Sleep (10000);
  5. return 100;
  6. }
  7. Private void methodcompleted (IAsyncResult asyncResult)
  8. {
  9. if (AsyncResult = = null) return;
  10. TextBox1.Text = (asyncresult.asyncstate as
  11. MyMethod). EndInvoke (AsyncResult). ToString ();
  12. }
  13. Private void button1_click (object sender, EventArgs e)
  14. {
  15. MyMethod my = method;
  16. IAsyncResult AsyncResult = My. BeginInvoke (methodcompleted, my);
  17. }

Note that the last two parameters of the BeginInvoke method are used here (if the called method contains parameters, these parameters will be used as the previous part of the BeginInvoke parameter, and if there are no parameters, the BeginInvoke will have only two parameters). The first parameter is the callback method delegate type, which has only one parameter, which is IAsyncResult, as shown in the Methodcompleted method. The Methodcompleted method is called automatically when the method methods are executed. The second parameter of BeginInvoke needs to pass some values to the Methodcompleted method, which can generally pass the delegate of the called method, such as my in the code above. This value can be obtained using the IAsyncResult.AsyncState property.

Because the above code accesses a textbox on the form asynchronously, you need to press CTRL+F5 to run the program (you cannot run the program directly by pressing F5, otherwise you cannot access the textbox in other threads, for if the GUI component is accessed in another thread, Detailed in the following sections). And put some other visual controls on the form, but after clicking on Button1, the other controls can still be used, as if nothing happened, and after 10 seconds, 100 will be output in TextBox1.

C # Threading Operations Vi. BeginXxx and EndXxx methods for other components

There are also methods like BeginInvoke and EndInvoke in other. Net components, such as the BeginGetResponse and EndGetResponse methods of the System.Net.HttpWebRequest class, and here is an example of using these two methods:

  1. Private void requestcompleted (IAsyncResult asyncResult)
  2. {
  3. if (AsyncResult = = null) return;
  4. System.Net.HttpWebRequest HWR =
  5. Asyncresult.asyncstate as System.Net.HttpWebRequest;
  6. System.Net.HttpWebResponse response =
  7. (System.Net.HttpWebResponse) Hwr. EndGetResponse (AsyncResult);
  8. System.IO.StreamReader sr = New
  9. System.IO.StreamReader (response. GetResponseStream ());
  10. TextBox1.Text = Sr. ReadToEnd ();
  11. }
  12. Private Delegate System.Net.HttpWebResponse Requestdelegate (
  13. System.Net.HttpWebRequest request);
  14. Private void button1_click (object sender, EventArgs e)
  15. {
  16. System.Net.HttpWebRequest request =
  17. (System.Net.HttpWebRequest)  System.Net.WebRequest.Create ("http://www.cnblogs.com");
  18. IAsyncResult AsyncResult =request. BeginGetResponse (requestcompleted, request);

C # six major threading operations

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.