【发布时间】:2016-08-07 00:03:09
【问题描述】:
每次我获得 UI 锁定时,我都无法从数据库中异步检索数据。
private async void RetrieveHotlist(object sender, RoutedEventArgs e) //button click
{
var hotItems = new ObservableCollection<HotItem>();
await Task.Factory.StartNew(() =>
{
try
{
var serv = "xxx";
string connStr = Common.GetConStrEF(serv + "\\" + Common.DBLOGIN_INSTANCE,
Common.DBLOGIN_DBNAME, Common.DBLOGIN_USER, Common.DBLOGIN_PASSWORD);
var dataModel = new xxxxDataModel(connStr);
foreach (var category in dataModel.SpecialNumberCategory) //retrieving database CreateObjectSet<SpecialNumberCategory>("SpecialNumberCategory"); //ObjectContext
{
var item = new HotItem() { Name = category.Name };
hotItems.Add(item);
}
}
catch (Exception exception)
{
var baseException = exception.GetBaseException();
MessageBox.Show("Error\n\n" + exception.Message + "\n\n" + baseException.Message);
}
});
if (Settings != null)
{
Settings.Hotlist.Clear();
foreach (var hotItem in hotItems)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => Settings.Hotlist.Add(hotItem)));
}
}
}
为什么 RetrieveHotlist 方法会锁定我的 UI?为什么 await Task.Factory.StartNew() 还不够?
感谢您的帮助:)
编辑:
为了更清楚,我删除了一些代码。
private void RetrieveHotlist(object sender, RoutedEventArgs e) //button click
{
var b = new BackgroundWorker();
b.DoWork += (o, args) =>
{
Thread.Sleep(2000); //**UI IS FULL RESPONSIVE FOR 2 sec.**
var hotItems = new ObservableCollection<HotItem>();
try
{
var serv = "xxxx";
var dataModel = new xxxxDataModel(connStr);
var c = dataModel.SpecialNumberCategory; //**UI FREEZE / ENTITY FRAMEWORK**
b.RunWorkerCompleted += (o, args) =>
{
};
b.RunWorkerAsync();
}
EDIT2: 感谢大家的帮助,实体框架导致了这个问题(我现在不知道为什么)。
我用 SqlConnection 和 SqlCommand 替换了所有模型行。现在效果很好。
【问题讨论】:
-
您应该在单独的线程上检索数据并显示消息对话框,UI 更改在另一个线程上。我们有所谓的 UI 线程,应该调用所有与 UI 相关的操作。
-
你确定上面是你的代码吗? await 只能和 async 方法一起使用,上面的代码甚至不能编译...
-
你确定下一行
hotItems.Add(item);没有抛出任何异常吗? -
@Ephraim 我已经尝试过使用后台工作人员,它是一样的。我会尝试使用新线程。
-
@Kylo Ren & StepUp - 代码正确,没有错误和异常:) StartNew 是等待的。
标签: c# wpf async-await