简体   繁体   English

Backgroundworker,没有运行进度条

[英]Backgroundworker, not running the progressbar

How can I fix this issue ? 我该如何解决这个问题?

I am expecting the progressbar to load during process untill process it is done 我期待进度条在进程中加载​​,直到进程完成

Here is my code: 这是我的代码:

private void btnProcess_Click(object sender, EventArgs e)
    {
        backgroundWorker.WorkerReportsProgress = true;
        backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
        backgroundWorker.DoWork += backgroundWorker_DoWork;

        backgroundWorker.RunWorkerAsync();
    }

    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        //start transaction
        DoTransaction();
    }

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

My transaction function: 我的交易功能:

private void DoTransaction()
    {
        string pathIdentifier;
        pathIdentifier = func.checkthePathFile();
        if (pathIdentifier == null)
        {
            MessageBox.Show("Path has no yet been specified!");
        }
        else
        {
            //create xml base from user inputs
            XElement transactXML = new XElement("Transaction",
                new XElement("CardNumber", txtCardNum.Text.Trim()),
                new XElement("ExpireDate", txtExpDate.Text.Trim()),
                new XElement("Cardtype", txtCardType.Text.Trim())
                );

            //save xml to a file
            transactXML.Save(pathIdentifier + "/sample.xml");
        }
    }

How is the runtime supposed to know how far along your process is? 运行时如何知道您的进程有多远?

You need to tell it by calling backgroundWorker.ReportProgress from the background operation. 您需要通过从后台操作调用backgroundWorker.ReportProgress来告诉它。 No magic here. 这里没有魔力。

MSDN: http://msdn.microsoft.com/en-us/library/ka89zff4.aspx MSDN: http//msdn.microsoft.com/en-us/library/ka89zff4.aspx

Break down your process into meaningful chunks and ReportProgress whenever it makes sense to do so. 只要有意义,就将进程分解为有意义的块和ReportProgress

public void DoTransaction()
{
    part1();
    backgroundWorker.ReportProgress(25);

    part2();
    backgroundWorker.ReportProgress(50);

    part3();
    backgroundWorker.ReportProgress(75);

    part4();
    backgroundWorker.ReportProgress(100);
}

Edit Based on Posting of Transaction() function 根据发布Transaction()函数进行编辑

If you are not confident in writing multithreaded programs, then do not attempt to write multithreaded programs, even with the help of a BackgroundWorker which tries to abstract some of those details away from you. 如果您对编写多线程程序没有信心,那么即使借助于试图从您那里抽象出一些细节的BackgroundWorker,也不要尝试编写多线程程序。

A few issues: 一些问题:

Your provided Transaction() method attempts to launch a MessageBox and read the Text property of various controls from the background thread. 您提供的Transaction()方法尝试启动MessageBox并从后台线程中读取各种控件的Text属性。 This is going to cause problems as the runtime typically throws an Exception when UI elements are accessed from a thread other than the one which created them. 这将导致问题,因为当从创建它们的线程以外的线程访问UI元素时,运行时通常会抛出异常。

If you really want to do the XML saving in the BackgroundWorker , you should validate the filename and directory, and save the Text properties to an intermediate object before setting up the BackgroundWorker and calling RunWorkerAsync . 如果您确实想在BackgroundWorker进行XML保存,则应在设置BackgroundWorker并调用RunWorkerAsync之前验证文件名和目录,并将Text属性保存到中间对象。

Furthermore, in my opinion, your Transaction method is not going to be time intensive enough to truly warrant a background thread. 此外,在我看来,您的Transaction方法不会足够时间来真正保证后台线程。 Even a relatively old PC will be able to create and save a 15 element XML file faster than you can blink. 即使是相对较旧的PC也能够以比闪烁更快的速度创建和保存15个元素的XML文件。 The runtime will probably waste more time marshalling data between the threads than it would to simply write the file out to disk. 运行时可能会浪费更多时间在线程之间编组数据,而不是简单地将文件写入磁盘。 Just do your work in the button click event handler. 只需在按钮单击事件处理程序中完成工作即可。

needs some reference to the BackgroundWorker instance.pass the reference to the class when instantiating it. 需要对BackgroundWorker实例的一些引用。在实例化时传递对类的引用。
instantiate like this 像这样实例化

BackgroundWorker worker = sender as BackgroundWorker;


then call like this 然后像这样打电话

`worker.ReportProgress(...)`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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