Wpf从数据库冻结UI中检索数据 [英] Wpf retrieving data from database freeze UI

查看:98
本文介绍了Wpf从数据库冻结UI中检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我有UI锁定问题。





为什么用户界面被冻结了?我认为不应该直到DownloadHotListAsync完成。



非常感谢。



我尝试过:



Hello everyone, I have a problem with UI locking.


Why the UI is freezed? I think it shouldn't be until DownloadHotListAsync finish.

Thanks a lot.

What I have tried:

private async void RetrieveHotlist(object sender, RoutedEventArgs e) //button click
        {
            await DownloadHotListAsync();
            if (_hotItems != null)
            {
                foreach (var hotItem in _hotItems)
                {
                    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => Settings.Hotlist.Add(hotItem)));
                }
            }
        }

        private ObservableCollection<HotItem> _hotItems;

        private async Task DownloadHotListAsync()
        {
            _hotItems = new ObservableCollection<HotItem>();
            await Task.Run(() =>
                {

                    try
                    {
                        var serv = "xxxxxx";
                        string connStr = Common.GetConStrEF(serv + "\\" + Common.DBLOGIN_INSTANCE,
                                                            Common.DBLOGIN_DBNAME, Common.DBLOGIN_USER, Common.DBLOGIN_PASSWORD);
                        var dataModel = new xxxDataModel(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);
                    }
                });
        }

推荐答案

检查一下,

1. c# - WPF中的列表视图使UI冻结数据绑定 - Stack溢出 [ ^ ]

2. c# - 防止wpf窗口挂起 - Stack Overflow [ ^ ]
Check this,
1. c# - A list view in WPF makes the UI frozen duing data binding - Stack Overflow[^]
2. c# - Preventing wpf window from hanging - Stack Overflow[^]


我可以建议一些更改吗?在按钮单击处理程序中的 await 语句之后,您将返回到调度程序线程,因此您不需要Dispatcher BeginInvoke。尝试自己武装线程通常不是一个好主意,你会陷入困境。将所有这些留给 async 方法。此外,处理异常的方式也不正确。只有在 await 语句中读取数据时,才会抛出异步方法中引发的任何异常。因此, try 块应位于 await 语句周围。最好使您希望以尽可能自包含的方式异步运行的方法。我会从它返回一个 ObservableCollection< hotitem>< / hotitem> 并将该方法折射成一个没有 try / catch 块。所以你最终得到这样的东西。

Could I suggest a few changes? After the await statement in the button click handler you are back on the dispatcher thread so you don’t need the Dispatcher BeginInvoke stuff. It is generally not a good idea to try to martial the threads yourself, you will get in a tangle. Leave all that to the async method. Also, the way you deal with exceptions is incorrect. Any exception raised in an asynchronous method is only thrown when the data is read at the await statement. So your try block should be positioned around the await statement. It’s best to make the method that you wish to run asynchronously as self contained as possible. I would return a ObservableCollection<hotitem></hotitem> from it and refractor the method into a standalone method without the try/catch blocks. So you would end up with something like this.

private ObservableCollection<HotItem> RetrieveHotList()
      {
          var _hotItems = new ObservableCollection<HotItem>();
          //..............

          return _hotItems;
      }

      private async Task<ObservableCollection<HotItem>> DownloadHotListAsync()
      {
          var _hotItems = new ObservableCollection<HotItem>();
          try
          {
              _hotItems = await Task.Run(() => RetrieveHotList());
          }
          catch (Exception ex)
          {
              //handle the exception
              //...............
          }
          return _hotItems;
      }


这篇关于Wpf从数据库冻结UI中检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆