C#編程應用–簡單線程

來源:互聯網
上載者:User

1. 主題:C#開發當中,多線程很多時候都必不可少的,尤其有處理多任務的情況下;

 

2. 有圖有真相:

 

3.源碼:

 

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

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.