最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【未解决】C#中添加始终滚动的进度条(跑马灯)和一格一格前进的滚动条(块)

C# crifan 4697浏览 0评论

【问题】
需要添加一个进度条,用于指示当前操作出于忙的状态,或者根据具体的步骤完成程度,按照比例显示完成的百分比。

【解决过程】
1.之前就已经搜了部分参考资料。
找到了,想要设置为跑马灯,即那种一种始终滚动,不停止的效果,是将对应的progressbar的style设置为Marquee:
pgbIndicator.Style = ProgressBarStyle.Marquee;
但是此处遇到的问题是,我已经是这样设置的了,但是结果去执行了那段很耗时的登陆网站的代码,结果这个progressbar,却消失了。
本以为是没有设置为可见,所以去:
pgbIndicator.Visible = true;
但是还是不行。
后来才明白,原来是执行耗时的那部分的代码,导致此处UI没有更新,所以没法显示对应的跑马灯的效果。
好像是要添加对应的不同的别的线程,来定期或不定期地更新进度条的滚动效果。

2.对于程序出于忙busy的状态,但是还想要进度条滚动显示的话,网上找了下,貌似有多种实现方法。
(1)http://topic.csdn.net/u/20070406/13/57816480-ea5b-4852-b8ed-4794e4a7971e.html
说用delegate。
(2)说用Animation的:
http://stackoverflow.com/questions/4723094/wpf-progressbar-doesnt-show-progress
(3)也有说用BackgroundWorker的:
http://stackoverflow.com/questions/1194620/how-do-i-display-progress-during-a-busy-loop
(4)还是这里解释的最全面:
http://stackoverflow.com/questions/1952201/display-progress-bar-while-doing-some-work-in-c
另外提到了:
BeginInvoke加EndInvoke
Application.DoEvents();

3.看了上面一堆的讨论,貌似还是用BackgroundWorker最简单。
然后去找了相关参考代码:
http://vbcity.com/forums/t/159137.aspx
后来也找到了微软的参考代码:
http://msdn.microsoft.com/en-US/library/hybbz6ke(v=vs.80).aspx
但是实际上使用过程中,很是郁闷,首先还是没有很简单的方法可以实现:
start();
doTimeConsumingWork();
end();
的形式,而且此处发现如果用了BackgroundWorker,即使是最简单的实现了,也还是需要,告诉BackgroundWorker自己所需要做的事情是什么,
即需要在doWork中写死每个BackgroundWorker要做的事情的,使用起来,可以说极为不便啊。
更要命的是,还不能打断点调试,否则到了断点位置,鼠标就变成忙状态,而无法继续调试,就会死掉。。。
被搞崩溃了,算了,果断放弃此方法。

4.后来自己去参考:
http://stackoverflow.com/questions/1952201/display-progress-bar-while-doing-some-work-in-c
http://stackoverflow.com/questions/1194620/how-do-i-display-progress-during-a-busy-loop
http://www.jppinto.com/2010/06/c-windows-form-is-busy-waiting-cursor-and-progress-bar-2/
结果写出来的代码:

private void btnInit_Click(object sender, EventArgs e)
{
    Thread thread = new Thread(doInit);
    thread.IsBackground = true;
    thread.Start(); 
}

delegate void showProgressbarDelegate(); 
public void showProgressbar()
{
    if (InvokeRequired)
    {
        this.BeginInvoke(new showProgressbarDelegate(showProgressbar), new object[] { });
        return;
    }

    pgbIndicator.Style = ProgressBarStyle.Marquee;
} 

private void doInit()
{
    showProgressbar();
    
    //do time consuming work ...
}

还是没法运行,会出现跨线程调用无法访问某参数的异常:

An unhandled exception of type ’System.InvalidOperationException’ occurred in System.Windows.Forms.dll:

Additional information: Cross-thread operation not valid: Contrl ‘trvSkydrive’accessed from a thread other than the thread it was created on.

system.invalidOperationException 异常

转载请注明:在路上 » 【未解决】C#中添加始终滚动的进度条(跑马灯)和一格一格前进的滚动条(块)

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.161 seconds, using 22.09MB memory