日期:2014-05-18  浏览次数:20785 次

请熟悉C#线程访问主线程控件的高手指点一下,感谢
namespace Httptest
{

  public partial class Form1 : Form
  {
  Thread mythread;
  public delegate void mydel();
  public Form1()
  {
  InitializeComponent();
  Mytimer mytimer1=new Mytimer();
  mythread=new Thread(new ThreadStart(Myzhumethod));
  // mythread.IsBackground = true; //设置后线程会随主线程结束 
  //如存在宿主进程vshost.exe 菜单栏下的 项目-属性-调试-启用调试器,把启用Visual Studio宿主进程这一项取消掉就OK了
  //原因:因为窗口运行的时候创建了前台线程,而前台线程会阻止进程终止,所以即使当窗口关闭但是进程一直无法结束。
  mythread.Start();
  mythread.Suspend();
  }

  。。。。。。。。。。。。。。。  


  public void Myzhumethod()
  {
  Mytimer mytimer1=new Mytimer();
  mydel mydel1 = new mydel(mytimer1.timecounter);
  this.Invoke(mydel1);
  }
  }







 public class Mytimer
  {
  public void timecounter()
  {
  int counter = 300;
  int i = 0;
  while (true)
  {
  Thread.Sleep(1000);
  counter--;
  Label3.TextBox = counter.ToString();
  if (counter == 0)
  {
   
  counter = 300;
  }
  }
  }
  }



经高人指点,想把类Mytimer里的 timecounter函数在运行过程中实时将counter值显示在主线程控件Label3中,我用了委托和Invoke,但运行时还报错说 上下文找不到Label3

请问我如何修改才能正常使用。

------解决方案--------------------
Label3在哪里定义?

一般Invoke的方法是Form的方法,你是new一个对象来invoke,很奇怪,这样应该没用,

timecounter应该作用Form的方法,不过看起来很奇怪,我想,你应该把Label3.TextBox = counter.ToString();
 这句提出来作为Form的一个方法,然后在timecounter中用invoke调用它,