C # multi-threaded Multi-parameter and return value usage

Source: Internet
Author: User

1. Pass parameters to the thread

1.1 Use lambda expressions

Thread t = new Thread(()=>Print("Hello from t"));t.Start();

Using this method, you can call a new thread to pass any parameter, or even put all methods into the 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 obtain the return value

Task
 
   task = Task.Factory.StartNew
  
   (()=>DownloadString("http://ww.linqpad.net"));RunSomeOtherMethod();String taskResult = task.Result;
  
 

It indicates that this Task returns a String result value. This value is returned by the DownloadString () method.

2.2 obtain the return value using asynchronous Delegation

Func
 
  
Method = Work; IAsyncResult cookie = method. beginInvoke ("test", null, null );////..... do other parallel work // int result = method. endInvoke (cookie );
 

Asynchronous delegation can pass any number of parameters to the thread to obtain any number of return values. generally, you need to define the Func delegate to point to the method to be executed in parallel. After the Func delegate execution method is executed, the result is saved in the IAsyncResult object and the return value is obtained through the EndInvoke method.


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.