C# Progressbar在winform中冻结
我正在尝试处理一个包含10000多行的文件,并将其存储在数据库中。处理一个文件通常需要2-3分钟,因此我想显示C# Progressbar在winform中冻结,c#,multithreading,winforms,progress-bar,C#,Multithreading,Winforms,Progress Bar,我正在尝试处理一个包含10000多行的文件,并将其存储在数据库中。处理一个文件通常需要2-3分钟,因此我想显示progressbar 该程序的问题是,Iprogressbar控件以及processForm中的label根本不显示。我在谷歌上搜索了几个小时,但还是没能解决它 这是我的密码 btnApplyEOD\u单击处理文件的方法 private void btnApplyEOD_Click(object sender, EventArgs e) { string url = txtE
progressbar
该程序的问题是,Iprogressbar
控件以及processForm
中的label
根本不显示。我在谷歌上搜索了几个小时,但还是没能解决它
这是我的密码
btnApplyEOD\u单击处理文件的方法
private void btnApplyEOD_Click(object sender, EventArgs e)
{
string url = txtEODReport.Text;
if (url != null)
{
using (var file = new System.IO.StreamReader(url))
{
int i = 0;
linesInEOD = File.ReadAllLines(url).Count();
if (backgroundWorkerEOD.IsBusy != true)
{
progressForm = new ProgressForm();
progressForm.Show();
backgroundWorkerEOD.RunWorkerAsync();
}
while ((line = file.ReadLine()) != null)
{
string[] splitLines = line.Split('~');
switch (splitLines[0])
{
case "01":
{
BOID = splitLines[1].Trim() + splitLines[2].Trim();
break;
}
.........
}
i++;
currentLine = i;
}
}
...........
bindToGridView();
}
}
我使用了BackgroundWorker
和BackgroundWorker\u dowwork
方法的代码如下:
private void backgroundWorkerEOD_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker workerEOD = sender as BackgroundWorker;
//for (int i = 1; i <= 10; i++) //usually works but useless for this scenario
//{
// workerEOD.ReportProgress(i * 10);
// System.Threading.Thread.Sleep(500);
//}
for (int i = 1; i <= linesInEOD; i++) // doesn't work at all but it will give accurate progressbar increase
{
workerEOD.ReportProgress(100 * currentLine / linesInEOD);
}
}
您正在UI线程中执行耗时的任务,所以冻结UI是正常的。我认为您应该将耗时的任务放到
BackgroundWorker
的DoWork
中,并调用backgroundWorker1.RunWorkerAsync()代码>需要时:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
this.PerformTimeConsumingTask();
}
public void PerformTimeConsumingTask()
{
//Time-Consuming Task
//When you need to update UI
progressForm.Invoke(new Action(() =>
{
progressForm.ProgressValue = someValue;
}));
}
如果你使用.NET 4.5,你也可以考虑使用模式。
你在UI线程中执行耗时的任务,所以冻结UI是正常的。我认为您应该将耗时的任务放到BackgroundWorker
的DoWork
中,并调用backgroundWorker1.RunWorkerAsync()代码>需要时:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
this.PerformTimeConsumingTask();
}
public void PerformTimeConsumingTask()
{
//Time-Consuming Task
//When you need to update UI
progressForm.Invoke(new Action(() =>
{
progressForm.ProgressValue = someValue;
}));
}
如果你使用.NET 4.5,你也可以考虑使用模式。
你应该把你的处理移到<代码> DoWork < /C>方法中。目前你的后台工作人员什么也不做,因为所有的处理都在UI线程上。@IvanStoev:是的,这就是问题所在。谢谢..您应该将处理移到DoWork
方法中。目前你的后台工作人员什么也不做,因为所有的处理都在UI线程上。@IvanStoev:是的,这就是问题所在。谢谢。我用了错误的方法,没有将处理任务分配给backgroundWorkerEOD\u DoWork
,而是将progressbar任务分配给DoWork
。这是我第一次使用WinForms
和progressbar
,所以我不知道自己做错了什么。感谢您指出问题。不客气:)您可能会发现我的描述也很有帮助。我做得不对,我没有将处理任务分配给BackgroundWorkerOd\u DoWork
,而是将progressbar任务分配给DoWork
。这是我第一次使用WinForms
和progressbar
,所以我不知道自己做错了什么。谢谢你指出这个问题。不客气:)你可能会发现我的描述也很有帮助。