【发布时间】:2018-01-06 08:43:03
【问题描述】:
我看过一些关于async 和await 的帖子以及它们的实际工作原理,但我还是有点困惑。假设我有两个 async 方法,我想确保第二个在第一个完成后开始。例如考虑这样的事情:
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
}
那么,确保发生这种情况的正确方法是什么?
更新:
为了尝试提供一个最小、完整和可验证的示例:
我在 WPF 应用程序中有 2 个 WCF 服务来与 Oracle WebCenter Content(UCM) 通信。这是我背后代码的最小版本:
UCM 服务添加新客户:
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 服务获取所有客户:
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);
}
在 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);
}
}
获取所有客户异步方法(Items 绑定到 UI 中的 DataGrid):
private async Task GetAllCustomers()
{
Items.Clear();
var searchResult = await GetCustomersInfoAsync();
if (!searchResult.HasError)
{
foreach (var item in searchResult)
Items.Add(new CustomerVm(item));
}
}
现在,当我添加一个新的Customer 时,我希望在我首先插入客户然后获取所有客户时在DataGrid 中看到新创建的项目。但是这段代码的行为是随机的,这意味着有时列表会在插入几秒钟后显示新创建的客户,有时则不会。
【问题讨论】:
-
使用
await后你不会收到任务,而是任务的结果。await将异步等待直到任务完成。 -
据我所知
await不会等待相关调用完成,如果您想确保完成t1然后t2开始,最好使用Wait()。 -
@Aria 不正确。
await顾名思义异步等待任务完成。不信请看this example -
@FCin:异步等待是什么意思?
-
@Bahman_Aries 我的意思是您的任务将一个接一个地执行而不会阻塞。这意味着您不会失去应用程序的响应能力。
标签: c# wpf asynchronous