Tell me about C # 's async and await.

Source: Internet
Author: User
Tags static class

Async and await are introduced in C # 5.0. These two keywords will make it easier for you to write asynchronous code.

Look at an example:

public class MyClass
{public
	MyClass ()
	{
		displayvalue ();//There's no blocking
		here. System.Diagnostics.Debug.WriteLine ("MyClass () end.");
	}
	Public task<double> Getvalueasync (double num1, double num2)
	{return
		Task.run (() =>
		{for
			( int i = 0; i < 1000000; i++)
			{
				num1 = num1/num2;
			}
			return NUM1;}
		);
	Public async void Displayvalue ()
	{
		Double result = await Getvalueasync (1234.5, 1.01); A new thread handles the Getvalueasync task here, and then the method returns immediately
		//all of the code after this is encapsulated as a delegate that is called
		when the Getvalueasync task completes System.Diagnostics.Debug.WriteLine ("Value is:" + result);
	}


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

As you can see, the async and await keywords simply make the above code easier to understand.

The output of the program is as follows:

MyClass () end.

Value is:2.47032822920623e-322


Here's a static Class I wrote to make it easy to perform an asynchronous invocation of a normal function:

	public static class Taskasynchelper {///<summary>///runs a method function asynchronously, executing a callback at the end of execution callback/// y>///<param name= "function" > Asynchronous method, this method has no parameters, the return type must be void</param>///<param name= "Callback" >
		The callback method that executes when the asynchronous method finishes executing, and the method has no parameters, and the return type must be void</param> public static async void Runasync (action function, action callback) {func<system.threading.tasks.task> Taskfunc = () => {return System.Threading.Tasks.Task.Run () =&gt
				;
				{function ();
			});
			};
			await Taskfunc ();
		if (callback!= null) callback (); ///<summary>///runs a method function asynchronously, executing a callback at the end of execution callback///</summary>///<typeparam name= "TResu Lt > The return type of the asynchronous method </typeparam>///<param name= "function" > Asynchronous method, which has no parameters, the return type must be tresult</param>///& Lt;param Name= The callback method executed at the end of the "callback" > Asynchronous method, the method parameter is TResult, and the return type must be void</param> public static async void Runasync<tresult> (func<tresult> function, action<Tresult> callback) {func<system.threading.tasks.task<tresult>> Taskfunc = () => {return S Ystem.
						Threading.Tasks.Task.Run (() => {return function ();
				});
			};
			TResult RLT = await taskfunc ();
		if (callback!= null) callback (RLT); }
	}

Use is very simple, the method name as a parameter into the line, the most common is the time-consuming serialization function to avoid blocking the UI process, causing the cotton phenomenon, affecting the user experience.


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.