AWS asynchronous APIs for .NET
The AWS SDK for .NET uses the Task-based Asynchronous Pattern (TAP) for its asynchronous
implementation. To learn more about the TAP, see Task-based Asynchronous Pattern (TAP)
This topic gives you an overview of how to use TAP in your calls to AWS service clients.
The asynchronous methods in the AWS SDK for .NET API are operations based on the Task
class or the
Task<TResult>
class. See docs.microsoft.com for information about these classes:
Task
class
When these API methods are called in your code, they must be called within a function that is declared
with the async
keyword, as shown in the following example.
static async Task Main(string[] args) { ... // Call the function that contains the asynchronous API method. // Could also call the asynchronous API method directly from Main // because Main is declared async var response = await ListBucketsAsync(); Console.WriteLine($"Number of buckets: {response.Buckets.Count}"); ... } // Async method to get a list of Amazon S3 buckets. private static async Task<ListBucketsResponse> ListBucketsAsync() { ... var response = await s3Client.ListBucketsAsync(); return response; }
As shown in the preceding code snippet, the preferred scope for the async
declaration is
the Main
function. Setting this async
scope ensures that all calls to AWS
service clients are required to be asynchronous. If you can't declare Main
to be asynchronous
for some reason, you can use the async
keyword on functions other than Main
and
then call the API methods from there, as shown in the following example.
static void Main(string[] args) { ... Task<ListBucketsResponse> response = ListBucketsAsync(); Console.WriteLine($"Number of buckets: {response.Result.Buckets.Count}"); ... } // Async method to get a list of Amazon S3 buckets. private static async Task<ListBucketsResponse> ListBucketsAsync() { ... var response = await s3Client.ListBucketsAsync(); return response; }
Notice the special Task<>
syntax that's needed in Main
when you use this
pattern. In addition, you must use the Result
member of the
response to get the data.
You can see full examples of asynchronous calls to AWS service clients in the Take a quick tour section (Simple cross-platform app and Simple Windows-based app) and in Code examples with guidance.