主线程尝试访问尚未由后台线程填充的数据

时间:2017-09-29 20:13:32

标签: c# background-process

我有一个需要10-15秒才能加载的UI。因此实现了后台线程(BG Thread)来加载数据。 当BG线程获取数据时,主线程开始执行代码的剩余部分,这就是问题开始的地方......即

当下面的步骤1由BG Thread执行时...主线程尝试执行步骤2

如何确保在从后台线程获取记录(步骤1)之前,第2步未执行?

所以,以下是执行的步骤..

===========This piece is executed only by BG Thread===============================================
Step 1. Get data from DB
   new Thread(() => 
   {
    Thread.CurrentThread.IsBackground = true; 
    My DB call goes here... and populates productCollection used in step 2 below
   }).Start();

==========================================================

Step 2.
if(productCollection?.Count > 0)  // This collection is always 0 becuase BG Thread (step 1) has not yet populated the collection and user get "No record message"
{

  // Filter collection based on some criteria
  // assign the filtered collection to datagrid
  dgProducts.DataSource = productCollection;      
}
else
{
 // show message to user that "No records found for given criteria";
}

1 个答案:

答案 0 :(得分:0)

你应该可以通过任务这样做。

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        SetDataSource();
    }

    public async void SetDataSource()
    {
        dgProducts.DataSource = await Task.Run(() =>
        {
            //My DB call goes here... and populates productCollection used in step 2 below
            return productCollection;
        });
    }
}

另一方面,如果你错了,查询真的需要10-15秒,这对你没有帮助。然后,您应该研究如何加速数据库内的数据库调用。