在WPF中使用EntityFrameWork加载数据时显示进度条

时间:2018-08-21 18:17:34

标签: c# sql-server wpf multithreading entity-framework

我想显示在Progressbar中从数据库中获取数据的进度。目前,我正在更新Button的内容。不知道如何在此代码中实现。

private async void FetchInvoicesDataFunc(object sender, RoutedEventArgs e)
 {
   ProgressBtn.Content = "Loading Data ...";
   InvoiceGrid.ItemsSource = await  Task.Run(FetchInvoiceDataAsync);
   ProgressBtn.Content = "Loaded !";

 }

private async Task<List<Invoice>> FetchInvoiceDataAsync()
 {
   List<Invoice> result;
   using(var context = new Intelliventory_DBEntities() )
    {  
      result  = await context.Invoices.Where(b => b.InvoiceID <= 2000).Include(x => x.Customer).ToListAsync();      
    }
        return  result;
    }
}

1 个答案:

答案 0 :(得分:2)

您将无法显示EF-Query的百分比,因为它不会通知您有关数据库查询的进度(我不知道有任何数据库系统可以使客户端了解查询状态)

您可以考虑将查询分为以下几个部分:

 private async void FetchInvoicesDataFunc(object sender, RoutedEventArgs e)
 {
   List<Invoice> results = new List<Invoice>();
   ProgressBtn.Content = "Loading Data ...";
   await Task.Run(async() => results.AddRange(await FetchInvoiceDataAsync(0, 500));  
   ProgressBtn.Content = "25% done...";
   await Task.Run(async() => results.AddRange(await FetchInvoiceDataAsync(501, 1000)); 
   ProgressBtn.Content = "50% done...";
   await Task.Run(async() => results.AddRange(await FetchInvoiceDataAsync(1001, 1500)); 
   ProgressBtn.Content = "75% done...";
   await Task.Run(async() => results.AddRange(await FetchInvoiceDataAsync(1501, 2000));        
   InvoiceGrid.ItemsSource = results;
   ProgressBtn.Content = "Loaded !";    
 }

 private async Task<List<Invoice>> FetchInvoiceDataAsync(int start, int end)
 {
   List<Invoice> result;
   using(var context = new Intelliventory_DBEntities() )
   {  
     result  = await context.Invoices.Where(b => b.InvoiceID >= start && b.InvoiceID <= end).Include(x => x.Customer).ToListAsync();      
   }

   return  result;
 }

请注意,这将对应用程序的性能产生负面影响。 在WinForms和WPF中都有成千上万的教程如何使用进度条,因此我不会深入探讨该主题。