Async methods can have the following return types:
Task, for an async method that performs an operation but returns no value.
Task<TResult>, for an async method that returns a value.
void, for an event handler.
Task return type
Async methods that don't contain a return statement or that contain a return statement that doesn't return an operand usually have a return type of Task. Such methods return void if they run synchronously. If you use a Task return type for an async method, a calling method can use an await operator to suspend the caller's completion until the called async method has finished.
Example:
In the following example, the WaitAndApologizeAsync
method doesn't contain a return
statement, so the method returns a Task object. Returning a Task
enables WaitAndApologizeAsync
to be awaited. The Task type doesn't include a Result
property because it has no return value.
public static async Task DisplayCurrentInfoAsync() { await WaitAndApologizeAsync(); Console.WriteLine($"Today is {DateTime.Now:D}"); Console.WriteLine($"The current time is {DateTime.Now.TimeOfDay:t}"); Console.WriteLine("The current temperature is 76 degrees."); } static async Task WaitAndApologizeAsync() { await Task.Delay(2000); Console.WriteLine("Sorry for the delay...\n"); }
Task<TResult> return type The Task<TResult> return type is used for an async method that contains
a return statement in which the operand is TResult. In the following example, the GetLeisureHoursAsync method contains a
return statement that returns an integer. Therefore, the method
declaration must specify a return type of Task<int>. The FromResult async
method is a placeholder for an operation that returns a DayOfWeek.
public static async Task ShowTodaysInfoAsync() { string message = $"Today is {DateTime.Today:D}\n" + "Today's hours of leisure: " + $"{await GetLeisureHoursAsync()}"; Console.WriteLine(message); } static async Task<int> GetLeisureHoursAsync() { DayOfWeek today = await Task.FromResult(DateTime.Now.DayOfWeek); int leisureHours = today is DayOfWeek.Saturday || today is DayOfWeek.Sunday ? 16 : 5; return leisureHours; }
No comments:
Post a Comment