C#5.0 Asynchronous Programming Async and Await--Specifications and Precautions for Asynchronous Methods

A few things to note about asynchronous methods:

There are three types of return values ​​for asynchronous methods:

1. void without any return value

2. Return the Task of a Task task to obtain the execution status of the asynchronous method

3. Return Task<T> to get the result and execution status of asynchronous method execution

See the example below:

If you think that your asynchronous task does not need to know its execution status (whether an exception occurs, etc.), you can use the void signature with no return value ( it is strongly recommended not to use void asynchronous methods in formal projects )

public static async void FireAndForget()
        {
            var myTask = Task.Run(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("DoWork : {0}", i);
                    Thread.Sleep(500);
                }
            });
            await myTask;
        }

If you need to know the execution status of the task, use the signature of the Task

static Task SayHello(string name)
        {
            return Task.Run(() =>
            {
                Console.WriteLine( " Hello: {0} " ,name);
            });
        }

        static async Task SayHelloAsync(string name)
        {
            await SayHello(name);
        }

If you need to get the result of an asynchronous method you can use the signature of Task<T>

 static Task<int> SumArray(int[] arr)
        {
            return Task.Run(() => arr.Sum());
        }

        static async Task<int> GetSumAsync(int[] arr)
        {
            int result = await SumArray(arr);
            return result;
        }

        static async void GetTaskOfTResult()
        {
            int [] arr = Enumerable.Range( 1 , 100 ).ToArray();
            Console.WriteLine("result={0}", GetSumAsync(arr).Result);

            int result = await GetSumAsync(arr);
            Console.WriteLine("result={0}", result);
        }

In addition to the above three examples of asynchronous methods, you can also use lambda expressions to create asynchronous methods by adding async before the lambda expression parameter and using await inside the expression.

public static void TestAsyncLambda()
        {
            Action act = async () =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("Do Work {0}", i);
                    await Task.Delay(500);
                }
            };
            act();
        }

As we can see from the above example, we can use the Task.Delay method to asynchronously wait for a method without blocking the execution of the thread

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325119328&siteId=291194637