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);
});
}