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

WinForm 多线程中给label赋值,不让访问???
源码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace mythread
{
  public partial class Form1 : Form
  {
  private int i=1;
  private Thread t;

  public Form1()
  {
  InitializeComponent();

  t = new Thread(new ThreadStart(MyThread));
  }

  private void button1_Click(object sender, EventArgs e)
  {
  t.Start();
  }

  private void button2_Click(object sender, EventArgs e)
  {
  // 停止线程
  }

  public void MyThread()
  {
  while (true)
  {
  label1.Text=i.ToString();
  i++;

  Thread.Sleep(500);
  }
  } 
  }
}

//抛的异常是:线程间操作无效:从不是创建控件"label1"的线程访问它

------解决方案--------------------
while (true) 

this.Invoke((MethodInvoker)delegate{
label1.Text=i.ToString(); 
});
i++; 

Thread.Sleep(500); 


------解决方案--------------------
public delegate void myEventHandler(string userStatus);
//来来个委托类, 线程中必用品。

public void MyThread() //线程

while (true) 

myEventHandler myevent=new myEventHandler(cc);
this.Invoke(myevent, i.ToString() );//线程中断调用UI线程的cc函数,调用UI函数完后,回到线程

i++; 

Thread.Sleep(500); 


public void cc(string userStatus)//UI线程处理UI变更
{
label1.Text= userStatus;
}


委托为中介,2个线程间切换