简体   繁体   English

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

[英]Main thread tries to access data not yet populated by Background thread

I have a UI which takes 10-15 seconds to load.我有一个需要 10-15 秒才能加载的 UI。 So implemented Background thread (BG Thread) to load data.于是实现了后台线程(BG Thread)来加载数据。 As BG Thread gets data, main thread starts to execute remainder of the code and this is where problem starts..ie当 BG 线程获取数据时,主线程开始执行剩余的代码,这就是问题开始的地方..ie

When step 1 below, is executed by BG Thread only... main thread tries to execute step 2当下面的第 1 步仅由 BG 线程执行时...主线程尝试执行第 2 步

How do I make sure that until I get records from background thread (Step 1), step 2 is not executed?如何确保在从后台线程(步骤 1)获取记录之前,不执行步骤 2?

So, here are the steps that gets executes..所以,这里是执行的步骤..

===========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";
}

You should be able to do it like this with a task.您应该能够通过任务来做到这一点。

 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;
        });
    }
}

On the other hand if you were wrong and the query just really takes 10-15 seconds this will not help you.另一方面,如果你错了,查询只需要 10-15 秒,这对你没有帮助。 Then you should be looking into how to speed up your DB Calls inside of your DB.然后你应该研究如何加速你的数据库内的数据库调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM