Asynchronous return type

Asynchronous return there the following types:

(1) .Task <TResult>, asynchronous method returns a value for

(2) .Task, for performing the method of the asynchronous operation but does not return any value.

(3) For the event handler.

A .Task <TResult> Return Type

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            string strInfo = ShowTodaysInfo().Result;
            Console.WriteLine(strInfo);
            Console.ReadKey();
        }
        private static async Task<string> ShowTodaysInfo()
        {
            string ret = String.Format("{0}", await GetLeisureHours());
            return ret;
        }

        static async Task<int> GetLeisureHours()  
        {  
            var today = await Task.FromResult<string>(DateTime.Now.DayOfWeek.ToString());  
            int leisureHours;  
            if (today.First() == 'S')  
            leisureHours = 16;  
            else  
                leisureHours = 5;  
     
            return leisureHours;  
        }  
    }
}

Two .Task return type

The method does not comprise an asynchronous or a return statement return statement operands do not return normally has a return type ,, Task Task If the return type of the asynchronous method, the method can be used to call await the operator to listen to how method call is completed, the call know asynchronous method is complete.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            ShowInfo().Wait();
            Console.WriteLine("主线程执行中。。。");
        }

        private async static Task ShowInfo()
        {
            Console.WriteLine("异步调用中");
            await Task.Delay(2000);
        }
        
    }
}

In the above code, the method ShowInfo () does not contain a return statement, but returned Task object representing ShowInfo waiting for completion.

 

Guess you like

Origin www.cnblogs.com/QingYiShouJiuRen/p/11228125.html