码迷,mamicode.com
首页 > 编程语言 > 详细

C#多线程编程实例 螺纹与窗口交互

时间:2015-08-21 15:15:33      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

C#多线程编程实例 螺纹与窗口交互

技术分享

代码:

    public partial class Form1 : Form
    {
        //声明线程数组
        Thread[] workThreads = new Thread[10];

        public Form1()
        {
            InitializeComponent();
        }

        //此托付同意异步的调用为Listbox加入Item
        delegate void AddItemCallback(string text);

        //这样的方法演示怎样在线程安全的模式下调用Windows窗口上的控件。

private void AddItem(string text) { if (this.listBox1.InvokeRequired) { AddItemCallback d = new AddItemCallback(AddItem); this.Invoke(d, new object[] { text }); } else { this.listBox1.Items.Add(text); } } //数据採集方法 public void DataGet() { while (true) { AddItem("ok"); Thread.Sleep(1000); } //假设此方法退出了,那么这个线程也就退出了 } /// <summary> /// 启动线程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //循环创建并启动线程运行 for (int i = 0; i < workThreads.Length; i++) { if (workThreads[i] == null) { //假设线程不存在,则创建 workThreads[i] = new Thread(new ThreadStart(DataGet)); workThreads[i].Name = i.ToString(); workThreads[i].Start(); } else { //已经存在,假设没有运行,则启动 if (workThreads[i].ThreadState == ThreadState.Aborted || workThreads[i].ThreadState == ThreadState.Stopped) { workThreads[i] = new Thread(new ThreadStart(DataGet)); workThreads[i].Name = i.ToString(); workThreads[i].Start(); }else{ workThreads[i].Start(); } } } } /// <summary> /// 停止线程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { //循环停止线程运行 for (int i = 0; i < workThreads.Length; i++) { //假设线程存在,而且状态不是停止也不是终止的,则终止该线程 if (workThreads[i] != null && workThreads[i].ThreadState != ThreadState.Stopped && workThreads[i].ThreadState != ThreadState.Aborted) { workThreads[i].Abort(); } } } }

源代码下载:http://download.csdn.net/detail/testcs_dn/7618881

版权声明:本文博客原创文章,博客,未经同意,不得转载。

C#多线程编程实例 螺纹与窗口交互

标签:

原文地址:http://www.cnblogs.com/lcchuguo/p/4747757.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!