我在獲取backgroundworker更新我的進度條時遇到了一些問題。我正在使用在線教程作爲示例,但我的代碼無法正常工作。我在這個網站上做了一些挖掘,找不到任何解決方案。我是背景工作者/進步的新手。所以我不完全理解它。C#WinForm BackgroundWorker沒有更新進度條
只是爲了設置: 我有一個主窗體(FORM 1),打開另一個(FORM 3)的進度條和狀態標籤。
我的表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();
}
所以。問題是它沒有更新任何東西。進度條和標籤正在更新。有人能指出我的寫作方向還是有建議嗎?
您是否設置了'BackgroundWorker.WorkerReportsProgress'? –
DoWork內部的代碼在while循環中,對嗎?不要簡化太多。 –