简体   繁体   中英

WPF main thread freezes while background thread is loading UI

I want to show progress bar while my application create complex screen. my code is:

protected override void LoadSubject(object sender)
    {
        var win = new Spinner();

        win.Show();

        Thread th = new Thread(() =>
        {
            LoadSubjectImpl(sender);

            win.Dispatcher.BeginInvoke(new Action(() => win.Close()));
        });

        th.Start();
    }

  private void LoadSubjectImpl(object sender)
    {
        Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                StartServiceWorkflow(sender);
            })
            );
    }

its works fine, but the progress bar freeze... I must use the dispatcher in background thread because of "InvalidOperationException" and I think that the problem, but what can I do?

  • spinner = costum progressbar.

You will have no luck trying to achieve what you have described. If you'd read closely that InvalidOperationException you would know that you cannot manipulate UI from background thread. What you have done using Dispatcher is synchronizing StartServiceWorkflow to UI thread. So your code is executing in it - that causes the freeze.

To achieve some user experience enhancement you can delegate to background thread tasks like reading form database or processing data that is to be displayed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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