C#3种工作线程访问控件

1.设置Control.CheckForIllegalCrossThreadCalls为false,告诉编译器不检查跨线程控件访问。

2.使用委托:

public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
  }

  private void button1_Click(object sender, EventArgs e)
  {
    String msg = "线程1";
    Thread th1 = new Thread(listBoxInvoke);
    th1.Start(msg);

    Thread th2 = new Thread(listBoxInvoke);
    msg = "线程2";
    th2.Start(msg);
  }

  delegate void listBoxInvokeDelegate(String item);

  private void listBoxInvoke(Object msg)
  {
    String message = (String)msg;
    if (listBox1.InvokeRequired)
    {
      lock (this)
      {
        listBoxInvokeDelegate lbd = new listBoxInvokeDelegate(listBoxInvoke);
        for (int i = 1; i < 10; i++)
        {
          listBox1.Invoke(lbd, msg+":"+i);
          Thread.Sleep(1000);
        }
      }
    }
    else
    {
      listBox1.Items.Add(msg);
    }
  }

}

3.使用BackgroundWorker控件,这是微软推荐的模式。

public partial class Form1 : Form
{
  public object msg { get; set; }
  public Form1()
  {
    InitializeComponent();
  }

  private void button1_Click(object sender, EventArgs e)
  {
    msg = "线程1:";
    bw1.RunWorkerAsync();
  }

  private void bw1_DoWork(object sender, DoWorkEventArgs e)
  {
    bw1.WorkerReportsProgress = true;
    for (int i = 0; i < 10;i++)
    {
      bw1.ReportProgress(0, msg+""+i);
      Thread.Sleep(1000);
    }
  }

  private void bw1_ProgressChanged(object sender, ProgressChangedEventArgs e)
  {
    listBox1.Items.Add(e.UserState.ToString());
  }

}

posted @ 2016-01-06 21:33  别让的礼物  阅读(315)  评论(0)    收藏  举报