在后台工作程序中实例化对象会导致UI冻结 [英] Instantiating an object in a background worker causes the UI to freeze up

查看:66
本文介绍了在后台工作程序中实例化对象会导致UI冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我目前拥有的,但是当我呼叫Dispatcher.BeginInvoke()时,我的UI冻结了:

This is what i have at the moment, but when i call Dispatcher.BeginInvoke(), my UI freezes up:

        BackgroundWorker backgroundWorker = new BackgroundWorker();
        backgroundWorker.WorkerSupportsCancellation = true;
        backgroundWorker.WorkerReportsProgress = true;


        ViewModel.GenerateReport(backgroundWorker, Dispatcher);

ViewModel:

ViewModel:

backgroundWorker.DoWork += delegate(object s, DoWorkEventArgs args)
        {
            try
            {
                ReportViewModel reportViewModel = new ReportViewModel(SessionContext, Mediator, reportDashboardViewModel.ReportRequest, false);

                dispatcher.BeginInvoke((Action)(() =>
                {
                    ReportPreviewView reportPreviewView = new ReportPreviewView(reportViewModel);
                    reportPreviewView.ReportName = reportDashboardViewModel.ReportRequest.Report.ReportName;

                    ReportView = reportPreviewView;
                }));
            }
            catch (Exception exception)
            {
                backgroundWorker.ReportProgress(0, "There Was an Error generating the report");
                backgroundWorker.CancelAsync();
                throw;
            }
        };

        backgroundWorker.RunWorkerAsync();

dispatcher.BeginInvoke中的第一行导致我的UI冻结. ReportPreviewView reportPreviewView = new ReportPreviewView(reportViewModel);

The first line in dispatcher.BeginInvoke causes my UI to freeze up. ReportPreviewView reportPreviewView = new ReportPreviewView(reportViewModel);

注意:ReportPreviewView为报告请求创建相关视图.可以是DevexpressC1pivot reports.

Note: ReportPreviewView creates the relevant view for the report request. May it be Devexpress, C1 or pivot reports.

一旦我删除了dispatcher.BeginInvoke,我就会收到此错误:

As soon as i remove the dispatcher.BeginInvoke, i get this error:

The calling thread must be STA, because many UI components require this.

所以我的问题是,我需要做些什么来解决这个问题?

So my question is, what do i need to do to get around this?

使用BackgroundWorker的全部原因是为了使我的UI始终保持响应状态.

The whole reason for using a BackgroundWorker was so that my UI stays responsive at all times.

我是multithreading的新手,所以也许我弄错了结构...

I am new to multithreading,so maybe i got the structure all wrong...

推荐答案

故事的故事,所有UI元素都需要在UI线程上创建!

Moral of the story, all UI elements needs to be created on the UI thread!

也就是说,如果UI元素的创建花费很长时间,则UI将冻结.承担所有沉重的重担并将其放在TaskBackgroundWorker中.

That being said, if the creation of the UI element takes a long time, the UI will freeze up. Take all the heavy lifting and put it in a Task or BackgroundWorker.

然后,您将拥有一个响应速度更快的UI.

Then you will have a more responsive UI.

这篇关于在后台工作程序中实例化对象会导致UI冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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