Thread Learning Notes

Source: Internet
Author: User

By the thread confused, make a note, I want to let the main thread is not affected by the case, in the newly opened thread execution, and give the result, the result is not very satisfied, the main thread is still not moving. We'll fix it later.

Defines the method, with the parameters of the
private string ThreadRun (string p_num) {int i = 0; Int. TryParse (TextBox1.Text, out i); String v_str = ""; for (int j = 1; J <= I; j + +) {v_str = j.tostring () + "\ r \ n" + v_str; } return V_STR; }//define delegate, private delegate string myinvokedelegate with parameters (string p_num); private void Button2_Click (object sender, EventArgs e) {string p_num = TextBox1.Text; Assignment myinvokedelegate task = new myinvokedelegate (ThreadRun); Declare the delegate//Use the BeginInvoke method to call the NewTask method asynchronously and pass in P_num as the NewTask parameter IAsyncResult asyncResult = task. BeginInvoke (p_num,null, NULL); The EndInvoke method will be blocked for 2 seconds//The EndInvoke method receives a IAsyncResult parameter that returns the return value of the NewTask method string result = task. EndInvoke (AsyncResult); Msgform f = new Msgform (result); F.show (); DoWork (); }

  

The following is useful for referencing someone else's content.

1. New Thread ()

A new thread is opened, executing a method with no arguments passed:

private void DoWork () {Thread t = new Thread (new ThreadStart (this). dosomething)); T.start ();} private void DoSomething () {MessageBox.Show ("thread Start");}

  

Open a new thread, execute a method, and pass the parameters:

private void DoWork () {Thread t = new Thread (new Parameterizedthreadstart (this). dosomething)); T.start ("Guozhijian");} private void DoSomething (object o) {MessageBox.Show (o.tostring ());}

The parameter is defined as the object type.
2. ThreadPool
As we all know, the cost of opening a new thread is very high, if we open a new thread for each operation, then it is too wasteful, so we use the thread pool below.
No parameter passing:

private void DoWork () {            ThreadPool.QueueUserWorkItem (new WaitCallback (this). dosomething));        }        private void DoSomething (object o) {            MessageBox.Show ("thread Start");        }

  

Parameters are passed:

private void DoWork () {            ThreadPool.QueueUserWorkItem (new WaitCallback (this). dosomething), "Guozhijian");        }        private void DoSomething (object o) {            MessageBox.Show (o.tostring ());        }

  

Using anonymous methods is more flexible:

private void DoWork () {            string name = "Guozhijian";            ThreadPool.QueueUserWorkItem (New WaitCallback (Delegate (object o) {                MessageBox.Show (name);            }));        

  

Local variables can be accessed directly in the anonymous code snippet without the problem of being concerned about parameter passing
Two. Invoke
1. This. Invoke
Now, after executing in the business thread, to change the value of the form control, if you get the handle of the control directly through this, and then operate on it, it throws an exception, and the. Net WinForm application does not allow such operations. This is, you can call the Invoke method

2.Invoke method Signature:
Object Control.Invoke (Delegate Method)
Object Control.Invoke (Delegate Method, params object[] args)

3. Using a custom delegate

private void DoWork () {            WaitCallback WC = new WaitCallback (this. dosomething);            ThreadPool.QueueUserWorkItem (WC, "Guozhijian");        }        Private delegate void Myinvokedelegate (string name);        private void DoSomething (object o) {this            . Invoke (New Myinvokedelegate (this). Changetext), o.tostring ());        }        private void Changetext (string name) {            this.textBox1.Text = name;        }

  

Oh, too much trouble, do I have to define a delegate every time ah, this can not.

4. Use System.Action:

private void DoWork () {            WaitCallback WC = new WaitCallback (this. dosomething);            ThreadPool.QueueUserWorkItem (WC, "Guozhijian");        }        private void DoSomething (object o) {this            . Invoke (New action<string> (this). Changetext), o.tostring ());        }        private void Changetext (string name) {            this.textBox1.Text = name;        }

  

This example passes a parameter, System.Action has a number of overloads, can have no parameters (non-generic), and can have up to four parameters, the same anonymous method, not using the generic form of System.Action, as follows:

private void DoWork () {            WaitCallback WC = new WaitCallback (this. dosomething);            ThreadPool.QueueUserWorkItem (WC, "Guozhijian");        }        private void DoSomething (object o) {this            . Invoke (New Action (delegate () {                this.textBox1.Text = o.tostring ();            }));        }

  


5. Using System.Func
If invoke invokes the main form operation, it also wants to get a return value after the call:

private void DoWork () {            WaitCallback WC = new WaitCallback (this. dosomething);            ThreadPool.QueueUserWorkItem (WC, "Guozhijian");        }        private void DoSomething (object o) {            system.func<string, int> f = new func<string, int> (this. GETID);            Object result = this. Invoke (F,o.tostring ());            MessageBox.Show (result. ToString ());        }        private int GetId (string name) {            this.textBox1.Text = name;            if (name = = "Guozhijian") {                return 999;            }            else {                return 0;            }        }

  


The value of result is 999.
System.Func also has many generic overloads, which are not mentioned here.

6. About the owner of Invoke: Control
This example is used to refer to this, where this is replaced by the handle of any one of the controls in the form is OK, because the Control.Invoke meaning is to delegate the method to the thread that owns the control to execute.

---------------------------------------------------------------

First, when to use multithreading for operations such as file operations, loading information from the network, and so on, you can use a thread to do these operations, a new thread to run other operations, increase the efficiency of the user experience. A typical example is the spelling checker in a Word program: one thread waits for user input, another thread searches the background, a third thread stores the data written in a temporary file, and a fourth thread downloads information from the Internet. Second, the simplest way for C # to use threading--the way in which a thread is used asynchronously to delegate C # is a simple way of using the Beginenvoke () method of the delegate (Delegate) and EndInvoke (). To use the BeginInvoke method step: 1. Create a function to execute such as the following code: using System;using system.collections.generic;using system.linq;using System.text;using System.threading;namespace mythread{Class Program {//create function private static int NEWTA            SK (int ms) {Console.WriteLine ("Task Start");            Thread.Sleep (MS);            Random random = new random (); int n = random.            Next (10000);            Console.WriteLine ("Mission Accomplished");        return n; The static void Main (string[] args) {}}} created a NewTask function that returns a type int that receives an int parameter that specifies the blocking time of the thread. 2. Create a delegate that can point to the method, that is, the parameter type and return type of the delegate is consistent with the function, as follows: Using system;using system.collections.generic;using system.linq;using System.text;using System.threading;namespace mythread{CLass Program {//create function 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;        }//create delegate private delegate int newtaskdelegate (int ms); static void Main (string[] args) {}}}3. Instantiates the newly created delegate and uses the instance's BeginInvoke method and EndInvoke method to make an asynchronous call to the function. Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;namespace Mythread{class Program {//create function private static int newtask (int ms) {Console.writel            INE ("task start");            Thread.Sleep (MS);            Random random = new random (); int n = random.            Next (10000);            Console.WriteLine ("Mission Accomplished");        return n;        }//create delegate private delegate int newtaskdelegate (int ms); static void Main (sTring[] (args) {//Instantiation of delegate newtaskdelegate task = NewTask; Use the BeginInvoke method to call the NewTask method asynchronously and pass in 2000 as the NewTask parameter IAsyncResult asyncResult = task.            BeginInvoke (+, NULL, NULL); The EndInvoke method will be blocked for 2 seconds//The EndInvoke method receives a IAsyncResult parameter that will return the return value of the NewTask method int result = task.             EndInvoke (AsyncResult);        Console.WriteLine (result); }}} about parameters and return values for BeginInvoke: It has the same parameters as the method you need to execute asynchronously, plus two optional parameters. The first parameter is a AsyncCallback delegate that references the method to invoke when the asynchronous call completes. The second parameter is a user-defined object that can pass information to the callback method. BeginInvoke immediately returns without waiting for the asynchronous call to complete. BeginInvoke returns IAsyncResult, which can be used to monitor the progress of an asynchronous call. About the return value of EndInvoke: The return value of the EndInvoke method is the return value of the called method. If the method that is called asynchronously (referred to as the NewTask method) has not yet been completed, EndInvoke will block the calling thread until the asynchronous invocation of the method (referred to as the NewTask method) completes, allowing the calling thread to execute.

  

Thread Learning Notes

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.