I've seen some posts about async and await and how these actually work, but I'm still a little confused. Suppose I have two async methods and I want to make sure that the second one starts after the first one is finished. For instance consider something like this:
public async Task MyMethod(Item x)
{
await AddRequest(x); // 1. Add an item asynchronously
// make sure 2 starts after 1 completes
await GetAllRequest(); // 2. get all items asynchronously
}
Then, what is the proper way of making sure this happens?
Update:
In order to try to provide a Minimal, Complete, and Verifiable example:
I have 2 WCF services in a WPF application to communicate with Oracle WebCenter Content(UCM). Here is the minimal version of my code behind:
UCM Service to add new customer:
public static async Task<ServiceResult> CheckInCustomer(Customer c)
{
CheckInSoapClient client = new CheckInSoapClient();
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
{
// an async method in Oracle WebContent services to insert new content
result = await client.CheckInUniversalAsync(c);
}
return new ServiceResult();
}
UCM Service to get all customer:
public static async Task<Tuple<ServiceResult, QuickSearchResponse>> GetAllCustomers()
{
ServiceResult error;
var result = new QuickSearchResponse();
SearchSoapClient client = new SearchSoapClient();
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
{
// an async method in Oracle WebContent services to search for contents
result = await client.QuickSearchAsync(queryString);
}
return new Tuple<ServiceResult, QuickSearchResponse>(error, result);
}
Add Customer Async method which is binded to a Button's command in UI:
private async Task AddCustomer()
{
var result = await CheckInCustomer(NewCustomer);
if (!result.HasError)
await GetAllCustomers();
}
public ICommand AddCustomerCommand
{
get
{
_addCustomerCommand = new RelayCommand(async param => await AddCustomer(), null);
}
}
Get all Customer Async method (Items is binded to a DataGrid in UI):
private async Task GetAllCustomers()
{
Items.Clear();
var searchResult = await GetCustomersInfoAsync();
if (!searchResult.HasError)
{
foreach (var item in searchResult)
Items.Add(new CustomerVm(item));
}
}
Now, when I add a new Customer, I expect to see the newly created item in the DataGrid as I first insert the customer and then get all the customers. But this code behaves in a random manner, meaning that sometimes the list shows the newly created customer a few seconds after the insertion and sometimes doesn't.
awaityou will not recieve a task, but the result of the task.awaitwill asynchronously wait until the task is finished.awaitdoesn't wait for the associated call to be completed, this is better to useWait()if you want ensuret1be completed and thent2started.awaitas the name suggests asynchronously waits for task to finish. If you don't believe me see this example