C # Multithreading parameter passing

Source: Internet
Author: User
1, through the entity class to pass (can pass multiple parameters and get return value), the demo is as follows:

Functions that need to be called in the thread:

namespace threadparameterdemo{public    class Functionclass    {public        static string TestFunction (string name , int age)        {            //internal processing omit            return name + "The ages are:" + Aging;}}    }

To encapsulate by entities:

namespace threadparameterdemo{///<summary>//Transition class///    </summary> public    class Transitionalclass    {        private string name = String. Empty;        private int age;        public string acceptresults = string. Empty;        Public Transitionalclass (string name, int age)        {            this.name = name;            This.age = age;        }        public void TestFunction ()        {            acceptresults = functionclass.testfunction (this.name, this.age);        }    }}

Call:

  private void Form1_Load (object sender, EventArgs e)        {            //Instantiate Threadwithstate class, provide parameters              Transitionalclass TC for thread = new Transitionalclass ("Jack");            Create the thread that performs the task and execute thread              t = new Thread (The new ThreadStart (TC). testfunction));            T.start ();            Gets the return value through Tc.acceptresults;          }


Small bet

You must be aware of the isbackground issue, and if IsBackground is false, the Windows program will not automatically exit the thread for you when it exits. That is, your application is actually not finished.

MSDN Recommendation: the best way to provide parameters for multithreaded method calls is to wrap the target method in a class and define fields for the class that will be used as parameters for the new thread.

The advantage of this approach is that any time you want to start a new thread, you can create a new instance of the class with its own parameters.

BackgroundWorker class

The functions in ThreadStart are not return values and arguments.

2. Parameters and return values in an asynchronous call
The perfect way to resolve parameters and return values is by using asynchronous calls. One of the biggest disadvantages of an asynchronous call compared to thread is that it cannot control its priority.

The specific code is as follows:

        Public delegate string Delegatefunction (string name,int age);//delegate        Delegatefunction DF;        private void Form1_Load (object sender, EventArgs e)        {            //points to the method that needs to be called            df = new Delegatefunction ( functionclass.testfunction);            String name = "My name";//input parameter             int age = n;            IAsyncResult result = df. BeginInvoke (name,age, NULL, NULL);            String myresult = df. EndInvoke (result);//For receiving return value             MessageBox.Show (myresult);        }

Simplified:

public func<string, int, string>  df;//delegate        private void Form1_Load (object sender, EventArgs e)        {            / /point to the method that needs to be called            df + = functionclass.testfunction;            String name = "My name";//input parameter             int age = n;            IAsyncResult result = df. BeginInvoke (name, age, NULL, NULL);            String myresult = df. EndInvoke (result);//For receiving return value             MessageBox.Show (myresult);        }

Small bet

The generation of new threads in this way is run in the background (background) with the priority of normal


3. Using BackgroundWorker

The simplest way to return multiple threads is to use the BackgroundWorker component to manage the thread, raise the event when the task completes, and then process the result with the event handler.

Small bet
The BackgroundWorker component is used to perform time-consuming asynchronous operations such as database transactions, file downloads, and so on.
Add an BackgroundWorker instance to the application, and if you are using VS, you can drag it directly from the tool to the application:

BackgroundWorker backgroundWorker1 = new BackgroundWorker ();

In order to begin operations in the background, you must call the RunWorkerAsync () method of BackgroundWorker, and when this party is called, BackgroundWorker starts the background operation by triggering the DoWork event, DoWork The code for the event is executed in another thread.
When the background operation is completed, either completed or cancelled, the runworkercompleted event is triggered, which can be used to feedback the results of the background operation to the user.
In addition, the cancelled property of the Runworkercompletedeventargs instance is passed to determine whether the cancel operation terminates the background operation.


The specific demo is as follows:


Using system;using system.windows.forms;namespace windowsformsapplication1{public partial class Form2:form {        Public Form2 () {InitializeComponent (); private void Form2_load (object sender, EventArgs e) {//transitionalclass TC = new Transitional            Class ("Xiaoming", 10);        ThreadPool.QueueUserWorkItem (New WaitCallback (transitionalclass.testfunction), TC); private void Button1_Click (object sender, EventArgs e) {this.        TESTAREA2 (); } private System.ComponentModel.BackgroundWorker BackgroundWorker1 = new System.ComponentModel.BackgroundWorker (        );            private void TestArea2 () {initializebackgroundworker ();            AreaClass2 AreaObject2 = new AreaClass2 ();            Areaobject2.base = 30;            Areaobject2.height = 40;            Start the asynchronous operation.        Backgroundworker1.runworkerasync (AREAOBJECT2);       } private void Initializebackgroundworker () {//Attach event handlers to the BackgroundWorker object. Backgroundworker1.dowork + = new System.ComponentModel.DoWorkEventHandler (backgroundworker1_dowork            ); backgroundworker1.runworkercompleted + = new System.ComponentModel.RunWorkerCompletedEventHandler (Background        worker1_runworkercompleted);  } private void Backgroundworker1_dowork (object sender, System.ComponentModel.DoWorkEventArgs e) {//When executing the DoWork event, DoWorkEventArgs The result property of the instance, returning the value to the user; in the runworkercompleted event, Runworkercompletedeventa            The result property of the RGS instance receives the value; AreaClass2 AreaObject2 = (AreaClass2) e.argument;            Return the value through the Result property.        E.result = Areaobject2.calcarea (); } private void Backgroundworker1_runworkercompleted (object sender, System.ComponentModel.Run Workercompletedeventargse) {//Access the result through the result property.            Double area = (double) e.result;        MessageBox.Show ("The area is:" + area.tostring ()); }    }}


Demo code from MSDN: Click to open link


Reference article: Click to open a link

4, if it is not as good as the return value, how to write gracefully? anonymous function.

The Functionclass class is new and the test function is as follows:

   public static void TestFunction2 (string name, int age)        {            //internal processing omitted                    }

The call is as follows:

private void Form1_Load (object sender, EventArgs e)        {            Thread t1 = new Thread (new ThreadStart (delegate            { C14/>functionclass.testfunction2 ("Eee", 5);            });            T1. Start ();                  }

Small bet

If you call through WCF, you should put the function of the thread on the server, if it is placed on the client, it is easy because the time limit of the WCF client, causing the main program's inexplicable crash.

The main reason for the crash is that the client WCF response time is limited.

The above is the C # multithreading parameter delivery content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.