MVVM: Update view's control visibility after completion of threadpool worker item in WPF NET 3.5

雨燕双飞 提交于 2019-12-07 20:34:28

Dispatcher.CurrentDispatcher is not the Dispatcher of the UI thread, because it

Gets the Dispatcher for the thread currently executing and creates a new Dispatcher if one is not already associated with the thread.

You should use the Dispatcher of the current Application instance:

ThreadPool.QueueUserWorkItem(o =>
{
    var result = getDataFromDatabase();

    Application.Current.Dispatcher.Invoke(() => 
    {
        LstUsers = result;
        IsSplashVisible = false;
    });            
});

Assuming that your TestViewModel constructor is called in the UI thread, you could have written it like shown below, where Dispatcher.CurrentDispatcher is called in the UI thread instead of a ThreadPool thread. However, the field is entirely redundant. You could always just call Application.Current.Dispatcher.Invoke().

public class TestViewModel
{
    private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;

    public TestViewModel()
    {
        IsSplashVisible = true;

        ThreadPool.QueueUserWorkItem(o =>
        {
            var result = getDataFromDatabase();

            _dispatcher.Invoke(() => 
            {
               LstUsers = result;
               IsSplashVisible = false;
            });            
        });
    }

    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!