簡體   English   中英

C#WinForm BackgroundWorker不更新進程欄

[英]C# WinForm BackgroundWorker not Updating Processbar

讓背景工作人員更新進度條時遇到了一些麻煩。 我以在線教程為例,但是我的代碼無法正常工作。 我在此站點上進行了一些挖掘,但找不到任何解決方案。 我是背景工作人員/進度方面的新手。 所以我不太了解。

只是為了進行設置:我有一個主窗體(FORM 1),它打開了另一個帶有進度條和狀態標簽的窗體(FORM 3)。

我的Form 3代碼如下:

public string Message
{
    set { lblMessage.Text = value; }
}

public int ProgressValue
{
    set { progressBar1.Value = value; }
}
public Form3()
{
    InitializeComponent();
}

我的表格1部分代碼:

private void btnImport_Click(object sender, EventArgs e)
{
    if (backgroundWorker1.IsBusy != true)
    {
        if (MessageBox.Show("Are you sure you want to import " + cbTableNames.SelectedValue.ToString().TrimEnd('$') + " into " + _db, "Confirm to Import", MessageBoxButtons.YesNo) == DialogResult.Yes)
        {
            alert = new Form3(); //Created at beginning
            alert.Show();
            backgroundWorker1.RunWorkerAsync();
        }
    }
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    int count = 0
    foreach(DataRow row in DatatableData.Rows)
    {
    /*... Do Stuff ... */
    count++;
    double formula = count / _totalRecords;
    int percent = Convert.ToInt32(Math.Floor(formula)) * 10;
    worker.ReportProgress(percent, string.Format("Completed record {0} out of " + _totalRecords, count));
    }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    alert.Message = (String) e.UserState;
    alert.ProgressValue = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    alert.Close();
}

所以。 問題是它沒有更新任何內容。 進度欄或標簽正在更新。 有人可以指出我的寫作方向或提出建議嗎?

這將為您提供0 * 10因為count_totalRecords是整數值,此處使用整數除法。 因此, count小於總記錄,則您的formula等於0

double formula = count / _totalRecords; // equal to 0
int percent = Convert.ToInt32(Math.Floor(formula)) * 10; // equal to 0

好吧,當所有工作完成時,您將擁有等於1 formula 但這就是進步沒有改變的原因。

這是正確的百分比計算:

int percent = count * 100 / _totalRecords;

您需要將INTEGER值強制轉換為DOUBLE,否則C#Math將/可能將其截斷為0:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
  var worker = (BackgroundWorker)sender;
  for (int count = 0; count < _totalRecords; count++) {
    /*... Do Stuff ... */
    double formula = 100 * ((double)count / _totalRecords); // << NOTICE THIS CAST!
    int percent = Convert.ToInt32(formula);
    worker.ReportProgress(percent, string.Format("Completed record {0} out of " + _totalRecords, count));
  }
}

您僅在工作完成之前報告進度

worker.ReportProgress(percent, string.Format("Completed record {0} out of " + _totalRecords, count));

// You exit DoWork right after reporting progress

嘗試在BackgroundWorker運行時定期報告進度。 還要檢查Jon的注釋,以確保WorkerReportsProgress設置為true。

所以我做了更多的工作來挖掘告訴對象的屬性,該屬性告訴對象未設置要去的功能:/

謝謝你的幫助

暫無
暫無

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

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