Async and await in C #

Source: Internet
Author: User

Learn..

First, let's write an example:


public class MyClass
{
Public MyClass ()
{
Calling this method does not block
Showvalue ();


Console.WriteLine ("MyClass () end.");
}
Public task<int> getvalueasync (int number1, int number2)
{
Return Task.run (() =>
{
for (var i = 0; i < 1000000; i++)
{
Number1 = Number1 + number2;
}
return number1;
});
}


Public async void Showvalue ()
{
A new thread is opened here to handle the Getvalueasync task, and then the method returns immediately
Double result = await Getvalueasync (2143, 55);


All code after this is encapsulated as a delegate that is invoked when the Getvalueasync task completes
Console.WriteLine ("Value is:" + result);
}


#region Other Instances
To print an incoming string asynchronously
Public async static Task<string> Asyncadd (String str)
{
string result = await pringstring (str);
return result;
}
Public async static Task<string> pringstring (String str)
{
Return to "Hello World" + str;
}
#endregion
}


An asynchronous Method Displayvalue () that async keyword tags is called in the MyClass constructor, and the Displayvalue () method executes an asynchronous task await () with a getvalueasync keyword tag. This asynchronous task must be a task or task<tresult> as the return value, and we see that the actual return type of the asynchronous task execution completes is void or tresult,displayvalue () method await All code after Getvalueasync () is executed when the asynchronous task completes.


The Displayvalue () method actually executes the following code:

public void Displayvalue ()
{
system.runtime.compilerservices.taskawaiter<double> awaiter = Getvalueasync (1234.5, 1.01). Getawaiter ();
Awaiter. OnCompleted (() =>
{
Double result = Awaiter. GetResult ();
System.Diagnostics.Debug.WriteLine ("Value is:" + result);
});
}

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.