简体   繁体   English

代码运行时,进度条(选取框)消失

[英]Progress Bar (marquee) disappears while code is running

I have a simple form with a button and a progress bar. 我有一个简单的表单,带有一个按钮和一个进度条。 User clicks the button to begin processing and the progress bar animates while the code runs. 用户单击按钮开始处理,进度条在代码运行时设置动画。 In this case, it's just a for loop. 在这种情况下,它只是一个for循环。 But the problem is that the progress bar only appears for a fraction of a second then disappears. 但问题是进度条只出现了几分之一秒然后就消失了。

private void button1_Click(object sender, EventArgs e)
{
    progressBar1.Style = ProgressBarStyle.Marquee;
    progressBar1.MarqueeAnimationSpeed = 100;

    for (int i = 0; i < 3; i++) { Thread.Sleep(1000); } // sleep 3 times for 1 second

}

I assume this happens because the frame is redrawn after the code continues? 我认为这是因为代码继续后重绘帧? So I tried running the for loop on another thread but it didn't seem to matter. 所以我尝试在另一个线程上运行for循环,但它似乎并不重要。

How can I get the bar to animate while the loop runs? 如何在循环运行时让条形图进行动画处理?

Thanks 谢谢

You can simply workaround this by including a call to Application.DoEvents() on each iteration of your loop. 您可以通过在循环的每次迭代中包含对Application.DoEvents()的调用来简单地解决此问题。

But this is not the best way to achieve this. 但这不是实现这一目标的最佳方式。

The recommended way is processing your loop inside another thread, like a BackgroundWorker, keeping your progressbar animating on the mainthread. 推荐的方法是在另一个线程(如BackgroundWorker)中处理循环,在mainthread上保持进度条的动画效果。

You can get some explanation here: Keeping your UI Responsive and the Dangers of Application.DoEvents 你可以在这里得到一些解释: 保持你的UI响应和Application.DoEvents的危险

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

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