首页 > 编程语言 > 详细

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

时间:2016-01-06 23:13:19      阅读:208      评论:0      收藏:0      [点我收藏+]

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());
  }

}

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

原文:http://www.cnblogs.com/hj-lxp/p/5107505.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!