进度条和后台工作在Windows应用程序中的问题 [英] Problems with progressbar and backgroundworkerin windows application

查看:64
本文介绍了进度条和后台工作在Windows应用程序中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Yogesh Sharma。我正在使用C#在Windows窗体中使用progressbar。我需要从我的C#代码中打开一个Corel Draw文件(.cdr)。执行此任务大约需要10秒钟,因此我想使用ProgressBar。我正在尝试使用BackgroundWorker。我的C#代码如下......



Hi, I am Yogesh Sharma. I am working with progressbar in Windows Forms using C#. I need to open a Corel Draw file(.cdr) from my C# code. It takes about 10 seconds to do this task, hence I want to use ProgressBar. I am trying it with BackgroundWorker. My C# code is as follows...

private void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;
    progressBar1.Value = 0;
    backgroundWorker1.RunWorkerAsync();
    CorelDRAW.Application cdr = new CorelDRAW.Application();
    cdr.OpenDocument(@"d:\xxx.cdr", 1);
    cdr.AppWindow.WindowState = cdrWindowState.cdrWindowMaximized;
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    for (int i = 1; i <= 10; i++)
    {
        // Perform a time consuming operation and report progress.
        System.Threading.Thread.Sleep(1000);
        worker.ReportProgress(i * 10);
    }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}





我的问题是当我点击button1时,ProgressBar没有显示任何进展。当任务完成时(i:e cdr文件被打开),进度条立即显示完整进度。我需要在打开cdr文件的过程中显示进度。



请帮助我在这里缺少或我的代码有什么问题?

任何帮助都将不胜感激。



My problem is that when I click on button1, ProgressBar doesn''n show any progress. And when the task is completed(i:e cdr file gets opened), progressbar shows the full progress immediately. I need to show the progress during the process of opening cdr file.

Please help what I am missing here or what is wrong with my code?
Any help will be appreciated.

推荐答案

你的问题是你在主(GUI)线程上打开.cdr文件。

虽然后台工作人员在后台运行并报告进度,但GUI线程正在忙于打开文件而无法更新进度。

(所有窗口控件都必须更新来自GUI线程,否则抛出异常)



如果希望界面保持响应,则需要将文件打开代码移动到后台工作程序。
Your problem is that you''re opening .cdr file on main (GUI) thread.
Although you have background worker running in background and reporting progress, GUI thread is busy opening file and can''t update progress.
(All window controls have to be updated from GUI thread, otherwise exception is thrown)

You need to move file open code to background worker if you want interface to remain responsive.


这篇关于进度条和后台工作在Windows应用程序中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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