.NET Tips and Tricks

Blog archive

Calling .NET Methods With and Without Async

Let's say that you have an asynchronous method -- a method that looks something like this one that returns a Customer object wrapped inside a Task object:

public async Task<Customer> GetCustomerById(string custId) {

You can call this method with or without the await keyword. The syntax with the await keyword looks like this:

Customer cust = await GetCustomerById("A123");

Using the await keyword launches the method (and any code that follows it in the calling method) on a separate thread. When the method finishes running, the Customer object is pulled from the Task object and, in this case, stuffed into the cust variable.

The syntax without the await keyword looks like this:

Task<Customer> cust = GetCustomerById("A123");

With this syntax, you get back the Task object that manages the GetCustomerById method ... and that's it. You can now treat this cust variable as you would any other object: pass it to other methods, return it from the method with this code, store it in a global variable, and so on. When you're ready to run the Task in the cust variable, you can do asynchronously by calling the cust variable's Start method.

This code will start the GetCustomerById method running but go right on to the next line of code following the Start method:

cust.Start();

Alternatively, you can retrieve the Customer object returned by the method synchronously by reading the cust variable's Result property.

This code will cause processing to stop dead on this line of code until the GetCustomerById method managed by the Task object returns a Customer object:

Customer custResult = cust.Result;

There's more that you can with a Task object than just call the Start method and read the Result property (in fact, you'll probably use them together). But my point is that it's worth remembering that if you want the Task object associated with your async method, you can have it.

Posted by Peter Vogel on 10/17/2019


comments powered by Disqus

Featured

Subscribe on YouTube