At the end of the async method, should I return or wait?

At the end of the async method returning the task, if I call another async method, I could either await or return to execute its task. What are the consequences of each?

  Task FooAsync() { return BazAsync(); // Option A } async Task BarAsync() { await BazAsync(); // Option B } 
+25
c # async-await
Jul 26 '13 at 16:58
source share
2 answers

You cannot return the task if the method itself is declared as async - so this will not work, for example:

 async Task BarAsync() { return BazAsync(); // Invalid! } 

This will require the return type Task<Task> .

If your method just does a little work and then calls only one asynchronization method, then your first option is great and means that it involves even fewer tasks. You should be aware that any exceptions that occur in your synchronous method will be passed synchronously, although, indeed, that is how I prefer to handle argument checking.

It is also a general template for implementing overload, for example. using a cancel token.

Just keep in mind that if you need to switch to expecting something else, you need to make the async method instead. For example:

 // Version 1: Task BarAsync() { // No need to gronkle yet... return BazAsync(); } // Oops, for version 2 I need to do some more work... async Task BarAsync() { int gronkle = await GronkleAsync(); // Do something with gronkle // Now we have to await BazAsync as we're now in an async method await BazAsync(); } 
+28
Jul 26 '13 at 17:03
source share

Check out this link for a description: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

 async Task<int> TaskOfTResult_MethodAsync() { int hours; // . . . // The body of the method should contain one or more await expressions. // Return statement specifies an integer result. return hours; } // Calls to TaskOfTResult_MethodAsync from another async method. private async void CallTaskTButton_Click(object sender, RoutedEventArgs e) { Task<int> returnedTaskTResult = TaskOfTResult_MethodAsync(); int intResult = await returnedTaskTResult; // or, in a single statement //int intResult = await TaskOfTResult_MethodAsync(); } // Signature specifies Task async Task Task_MethodAsync() { // . . . // The body of the method should contain one or more await expressions. // The method has no return statement. } // Calls to Task_MethodAsync from another async method. private async void CallTaskButton_Click(object sender, RoutedEventArgs e) { Task returnedTask = Task_MethodAsync(); await returnedTask; // or, in a single statement //await Task_MethodAsync(); } 
+1
Jul 26 '13 at 17:01
source share



All Articles