C # example of method-to-asynchronous Conversion,

Source: Internet
Author: User

C # example of method-to-asynchronous Conversion,

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; using System. threading. tasks; namespace Asiainfo e-commerce {public class Program2 {public static void Main (string [] args) {Console. writeLine ("main thread 1"); AsyncTest. toAsync () => {Thread. sleep (1, 3000); Console. writeLine ("let me use a new thread for execution, Master thread for your work") ;}, () =>{ Console. writeLine ("Callback") ;}); AsyncTest. toAsync <string> (() ==>{ Thread. sleep (1000); return "female pig and male pig are married" ;}, p =>{ Console. writeLine ("Callback Result:" + p) ;}); Console. writeLine ("main thread 2"); Console. readLine ();}} /// <summary> /// convert a common method to an Asynchronous Method // </summary> public class AsyncTest {/// <summary> // parameter, convert a method with no return value to an Asynchronous Method /// </summary> /// <param name = "srcAction"> method to be converted </param> /// <param name = "callBack"> callBack method </param> public static async Task ToAsync (Action srcAction, Action callBack) {// defines an Asynchronous Method without return values. The following code may be a bit like Func <Task> task = () => {return Task. run () =>{ srcAction () ;}; await task (); if (callBack! = Null) {callBack ();}} /// <summary> /// convert a method without parameters and return values to an Asynchronous Method /// </summary> /// <typeparam name = "T"> generic template type </typeparam> /// <param name = "srcFunc"> source method to be transferred </param> /// <param name = "callBack"> callBack </ param> public static async Task ToAsync <T> (Func <T> srcFunc, action <T> callBack) {Func <Task <T> task = () => {return Task <T>. run () =>{ return srcFunc () ;}; var result = await task (); if (callBack! = Null) {callBack (result );}}}}

 

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.