吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 10211|回复: 5
收起左侧

[其他转载] c#启动线程与终止线程

 关闭 [复制链接]
sijin 发表于 2008-11-24 22:14
namespace ThreadExample
{
    public partial class Form1 : Form
    {
        StringBuilder sb = new StringBuilder();
        Thread thread1;
        Thread thread2;

        public Form1()
        {
            InitializeComponent();
        }
        private void AppendString(string s)
        {
            lock (sb)
            {
                sb.Append(s);
            }
        }
        public void Method1()
        {
            while (true)
            {
                Thread.Sleep(100);   //线程休眠100毫秒
                AppendString("a");
            }
        }
        public void Method2()
        {
            while (true)
            {
                Thread.Sleep(100);   //线程休眠100毫秒
                AppendString("b");
            }
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            sb.Remove(0, sb.Length);
            timer1.Enabled = true;
            thread1 = new Thread(new ThreadStart(Method1));
            thread2 = new Thread(new ThreadStart(Method2));
            thread1.Start();
            thread2.Start();
        }

        private void buttonAbort_Click(object sender, EventArgs e)
        {
            thread1.Abort();
            thread1.Join(10);
            thread2.Abort();
            thread2.Join(10);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (thread1.IsAlive == true || thread2.IsAlive == true)
            {
                richTextBox1.Text = sb.ToString();
            }
            else
            {
                timer1.Enabled = false;
            }
        }
    }
}

[ 本帖最后由 sijin 于 2008-11-24 22:21 编辑 ]

ThreadExample.rar

35.57 KB, 下载次数: 13, 下载积分: 吾爱币 -1 CB

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

zhaoxili 发表于 2009-6-6 01:53
来看看了 刚学习啊
SoftCheck 发表于 2010-3-26 16:54
弱弱的建议一下,如果在没有点击 buttonStart 按钮时点击了buttonAbort按钮,可能会发生异常,建议能加个处理机制,有助于程序的健壮性:)eee
hxy100 发表于 2010-5-2 02:08
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-16 11:14

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表