简体   繁体   English

C#进度栏不显示WinForm

[英]C# progress bar doesn't show WinForm

What happens is when I click the button to run my code my win form locks up and my progress bar doesn't run. 发生的事情是,当我单击按钮运行代码时,我的获胜表格被锁定并且进度条没有运行。 What am I doing wrong? 我究竟做错了什么?

foreach (string barcount in idit)
{
    barcountmax++;
}

label2.Text = "Total entries:  " + barcountmax;   
progressBar1.Minimum = 0;
progressBar1.Maximum = barcountmax;

...

foreach (string ids in idit)
{
    string[] splitids = ids.Split('|');
    string fixcommacrap = "";
    barmovement++;
    progressBar1.Value = barmovement;
}

My Winform just locks and freezes, i'm unable to see the progress bar. 我的Winform只是锁定并冻结,我看不到进度栏。

My guess is that you're doing all the work in the UI thread. 我的猜测是您正在UI线程中完成所有工作。 Don't do that. 不要那样做

Use BackgroundWorker to do the work, periodically updating the progress bar appropriately, using ReportProgress to allow the UI change to be made in the UI thread. 使用BackgroundWorker进行工作,定期更新进度条,并使用ReportProgress允许在UI线程中进行UI更改。

If you search for BackgroundWorker tutorials you'll find a whole bunch of them, such as this one . 如果您搜索BackgroundWorker教程,您会发现很多,例如this Many will give examples using progress bars, as BackgroundWorker is pretty much designed for that scenario. 许多人将使用进度条给出示例,因为BackgroundWorker是针对该场景而设计的。

By default if you are running a long operation the winform is not going to repaint itself. 默认情况下,如果您要进行长时间的操作,则winform不会自行重绘。 To fix it consider: 要解决此问题,请考虑:

  1. Running your computations on a separate thread, preferably using BackgroudWorker 在单独的线程上运行计算,最好使用BackgroudWorker
  2. Repainting it manually every time you change your progress bar. 每次更改进度条时,都需要手动重绘。

(1) is strongly recommended. 强烈建议(1)。

For that to work, you need to let the form paint when necessary. 为此,您需要在必要时让表单绘画。 The correct / preferred way is to use a worker thread (perhaps BackgroundWorker) for the long running tasks, calling back to the UI thread periodically to ask it to update the progress. 正确的/首选方法是对长时间运行的任务使用工作线程(也许是BackgroundWorker),并定期回调UI线程以要求其更新进度。

There is also DoEvents, but that is (frankly) a hack. 也有DoEvents,但是(坦率地说)这是一种hack。

The easiest but not correct way to fix the issue is to use the following inside your loop: 解决此问题的最简单但不正确的方法是在循环中使用以下代码:

Application.DoEvents();

The more challenging is to use separate thread for calculations and current UI thread for updating the progress bar. 更具挑战性的是使用单独的线程进行计算,并使用当前的UI线程来更新进度条。

As suggested, use a BackGroundWorker. 根据建议,使用BackGroundWorker。

In the worker, DO NOT update the ProgressBar directly, do it with BeginInvoke. 在工作进程中,请勿直接更新ProgressBar,而应使用BeginInvoke进行更新。

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

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