C# 线程中调用控件出错

来源:互联网 发布:手机淘宝支付宝在哪里 编辑:程序博客网 时间:2024/06/05 05:26
C# 线程中调用控件出错

 C# 线程中调用控件出错,可以用delegate和invoke解决。


using System;

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


namespace WindowsFormsApplication1
{
 public delegate void Defa();
 public partial class Form1 : Form
 {
  static int i = 0;
  Thread T1;
  public Form1()
  {
   InitializeComponent();
     
  }


  private void button1_Click(object sender, EventArgs e)
  {
    T1 = new Thread(new ThreadStart(SetLabelThread));
    T1.Start();
 




  }
  public void SetLabelThread()
  {
   while (i < 10)
   {
    if (label1.InvokeRequired)
    {
     Defa fun = new Defa(SetLabel);
     label1.Invoke(fun);
    }
   
   
    Thread.Sleep(500);
   }
  }
  public void SetLabel()
  {
    label1.Text = i++.ToString();
  
  }


  private void Form1_FormClosed(object sender, FormClosedEventArgs e)
  {
   T1.Abort();
  }
  
 }
}
0 0