如何等待运行异步方法的任务

时间:2018-06-22 08:55:01

标签: c# wpf entity-framework nested async-await

我正在编写WPF应用,最近开始使用await / async,因此GUI线程不会执行任何耗时的操作。

我的问题是我想使用实体框架从db异步加载两个集合。我知道我无法在DbContext上调用两个ToListAsync()方法,所以我想使用任务。

我编写了一个异步方法 LoadData(),该方法应等待完成LoadNotifications()之后再调用LoadCustomers()

但是,当执行执行到await this.context.MailingDeliveryNotifications.ToListAsync();时,它会创建另一个任务,并且以某种方式不关心我的task.Wait()方法中的LoadData(),因此它在调用LoadCustomers()之前完成对DbContext的第一次调用。

代码:

    public async void LoadData()
    {
        Task task = this.LoadNotifications();
        task.Wait();
        await this.LoadCustomers();
    }

    private Task LoadNotifications()
    {
        return Task.Run(() => this.LoadNotificationsAsync());
    }

    private async void LoadNotificationsAsync()
    {
        List<MailingDeliveryNotification> res = await this.context.MailingDeliveryNotifications.ToListAsync();
        this.Notifications = new ObservableCollection<MailingDeliveryNotification>(res);
    }

    private Task LoadCustomers()
    {
        return Task.Run(() => this.LoadNotificationsAsync());
    }

    private async void LoadCustomersAsync()
    {
        List<Customer> res = await this.context.Customers.ToListAsync();
        this.Customers = new ObservableCollection<Customer>(res);
    }

我知道我可以使用此代码解决此问题

    public async void LoadData()
    {
        List<MailingDeliveryNotification> res = await this.context.MailingDeliveryNotifications.ToListAsync();
        this.Notifications = new ObservableCollection<MailingDeliveryNotification>(res);

        List<Customer> res2 = await this.context.Customers.ToListAsync();
        this.Customers = new ObservableCollection<Customer>(res2);
    }

但是当我需要添加另一个集合以从db加载时,此方法将变得更多。我想保持代码干净。

1 个答案:

答案 0 :(得分:3)

简化代码:

public async Task LoadDataAsync()
{
    await LoadNotificationsAsync();
    await LoadCustomersAsync();
}

private async Task LoadNotificationsAsync()
{
    var res = await context.MailingDeliveryNotifications.ToListAsync();
    Notifications = new ObservableCollection<MailingDeliveryNotification>(res);
}

private async Task LoadCustomersAsync()
{
    var res = await context.Customers.ToListAsync();
    Customers = new ObservableCollection<Customer>(res);
}

或者可能只是:

public async Task LoadDataAsync()
{
    Notifications = new ObservableCollection<MailingDeliveryNotification>(
        await context.MailingDeliveryNotifications.ToListAsync());

    Customers = new ObservableCollection<Customer>(
        await context.Customers.ToListAsync());
}