C # multithreading multi-parameter and return-value usage

Source: Internet
Author: User

1. Pass parameters to the thread

1.1 Using lambda expressions

Thread t = new Thread (() =>print ("Hello from T"));
T.start ();

This way you can make a new thread pass any argument, or even put the method into the implementation into a lambda expression.

New Thread (string name, String value) =>{console.writeline (name);
Console.WriteLine (value);}). Start ();


2. Get the thread return value

2.1 Use Task to get return value

task<string> task = task.factory.startnew<string> (() =>downloadstring ("http://ww.linqpad.net"));
Runsomeothermethod ();
String Taskresult = task. result;

<String> to indicate that this Task returns a String result value. This value is the Downloadstring () method that returns a value.

2.2 Get return value using asynchronous delegate

Func<string, int> method = Work;
IAsyncResult Cookie = method. BeginInvoke ("Test", null,null);
//
//..... Do other parallel work
//
int result = method. EndInvoke (cookie);

An asynchronous delegate can pass any number of arguments to a thread to get any number of return values. It is usually necessary to define the Func delegate, point to the method to be executed in parallel, Func the result of the delegate execution method to the IAsyncResult object, and fetch the return value through the EndInvoke method.


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.