如何使用事件和代理更新UI的进度

时间:2011-12-10 16:48:01

标签: c# winforms events delegates

我在winform中有一个按钮,点击后会有一些处理5s。

在此过程中,我想将进度(ProgressBar)更新为UI,并完成工作的百分比。

如何使用Events& amp;代表?

其他方法(活动和代表除外)也受到欢迎。

2 个答案:

答案 0 :(得分:5)

如果要在此过程中保持应用程序的响应,请使用BackgroundWorker。请参阅MSDN文章BackgroundWorker Class。它有一个c#示例,显示如何报告进度。

答案 1 :(得分:1)

下面的伪代码。我手头没有编译器,所以实际的ProgressBar界面可能与我记忆中的略有不同。

// service

delegate void ProgressDelegate( int CurrentValue, int MaxValue );

void BusinessProcess( ProgressDelegate progress )
{
   // do something
   progress( 20, 100 );

   // do other things
   progress( 50, 100 );

   // do yet another thing
   progress( 100, 100 );
}

// client

void Button1_Click( object sender, EventArgs e )
{
   BusinessProcess(
      (current, max ) => 
      {
         this.ProgressBar1.Maximum = max;
         this.ProgressBar1.Value = current;
         this.ProgressBar1.Refresh();
      }
      );
}
相关问题