簡體   English   中英

Backgroundworker,沒有運行進度條

[英]Backgroundworker, not running the progressbar

我該如何解決這個問題?

我期待進度條在進程中加載​​,直到進程完成

這是我的代碼:

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;
    }

我的交易功能:

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");
        }
    }

運行時如何知道您的進程有多遠?

您需要通過從后台操作調用backgroundWorker.ReportProgress來告訴它。 這里沒有魔力。

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

只要有意義,就將進程分解為有意義的塊和ReportProgress

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

    part2();
    backgroundWorker.ReportProgress(50);

    part3();
    backgroundWorker.ReportProgress(75);

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

根據發布Transaction()函數進行編輯

如果您對編寫多線程程序沒有信心,那么即使借助於試圖從您那里抽象出一些細節的BackgroundWorker,也不要嘗試編寫多線程程序。

一些問題:

您提供的Transaction()方法嘗試啟動MessageBox並從后台線程中讀取各種控件的Text屬性。 這將導致問題,因為當從創建它們的線程以外的線程訪問UI元素時,運行時通常會拋出異常。

如果您確實想在BackgroundWorker進行XML保存,則應在設置BackgroundWorker並調用RunWorkerAsync之前驗證文件名和目錄,並將Text屬性保存到中間對象。

此外,在我看來,您的Transaction方法不會足夠時間來真正保證后台線程。 即使是相對較舊的PC也能夠以比閃爍更快的速度創建和保存15個元素的XML文件。 運行時可能會浪費更多時間在線程之間編組數據,而不是簡單地將文件寫入磁盤。 只需在按鈕單擊事件處理程序中完成工作即可。

需要對BackgroundWorker實例的一些引用。在實例化時傳遞對類的引用。
像這樣實例化

BackgroundWorker worker = sender as BackgroundWorker;


然后像這樣打電話

`worker.ReportProgress(...)`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM