-4
我有一个需要10-15秒才能加载的UI。所以实现后台线程(BG Thread)来加载数据。 当BG线程获取数据时,主线程开始执行代码的其余部分,这就是问题开始的地方。主线程尝试访问尚未填充的数据后台线程
当步骤如下1,由BG只主题...主线程试图执行步骤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";
}
为什么不使用'async' /'await'? – johnnyRose
在异步/等待的情况下,加载数据的时间相同,但没有变化。我曾尝试使用下面的示例异步/等待。 http://www.c-sharpcorner.com/article/async-and-await-in-c-sharp/ – Amit
这就是异步/等待的整点。除非可以同时进行多个调用,否则最终会等待相同的时间(_especially_如果它现在需要15秒!),但使用异步意味着编译器会为您管理它。所以你不必担心强行创建新线程。但真正的价值在于知道数据何时完成加载,就像您的问题所要求的一样; “等待”为你做。 – johnnyRose