欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WinForm中BackgroundWorker控件用法简单实例

程序员文章站 2023-08-17 16:23:30
本文实例讲述了winform中backgroundworker控件用法。分享给大家供大家参考。具体如下: using system; using system....

本文实例讲述了winform中backgroundworker控件用法。分享给大家供大家参考。具体如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
namespace winformapp
{
 public partial class form2 : form
 {
  backgroundworker backgroundworker;
  int i = 0;
  int len = 100;
  public form2()
  {
   initializecomponent();
   backgroundworker = new backgroundworker();
   backgroundworker.dowork += new doworkeventhandler(backgroundworker_dowork);
   backgroundworker.runworkercompleted += new runworkercompletedeventhandler(backgroundworker_runworkercompleted);
   backgroundworker.progresschanged += new progresschangedeventhandler(backgroundworker_progresschanged);
   backgroundworker.workerreportsprogress = true;
  }
  void backgroundworker_progresschanged(object sender, progresschangedeventargs e)
  {
   threadinvoke.setmethodinvokevalue(label2, "进度:" + e.progresspercentage.tostring());
   //progressbar.value = e.progresspercentage;
  }
  void backgroundworker_runworkercompleted(object sender, runworkercompletedeventargs e)
  {
   threadinvoke.setmethodinvokevalue(label3, "结果:completed");
  }
  void backgroundworker_dowork(object sender, doworkeventargs e)
  {
   threadinvoke.setmethodinvokevalue(label3, "结果:start");
   while (i < len)
   {
    i++;
    system.threading.thread.sleep(100);
    threadinvoke.setmethodinvokevalue(label1, "工作:" + (i * 10).tostring());
    backgroundworker.reportprogress(i);
    application.doevents();
   }
  }
  private void button1_click(object sender, eventargs e)
  {
   backgroundworker.runworkerasync();
  }
 }
}

希望本文所述对大家的c#程序设计有所帮助。