c# 多線程基本操作

來源:互聯網
上載者:User
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 winfromDeom
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button2.Enabled = false;
        }

        //聲名一個線程
        public Thread t;

        public delegate void upUI();

        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            button1.Enabled = false;
            button2.Enabled = true;
            //實列化一個線程
            t = new Thread(new ThreadStart(doThread));
            //設定是否是後台執行的線程
            t.IsBackground = true;
            //開始執行這個線程
            t.Start();

        }

        private void doThread()
        {
            //更新UI委託
            upUI upui = new upUI(upDataUi);
            
            try
            {
                while (true)
                {
                    Thread.Sleep(0);
                    //開始更新UI
                    this.Invoke(upui);
                }
            }
            finally
            {
                Thread.Sleep(5000);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //設定為終止狀態
            t.Abort();
            //阻塞這個線程
            t.Join();
            button1.Enabled = true;
            button2.Enabled = false;
        }
        /**//// <summary>
        /// 執行UI更新的方法
        /// </summary>
        private void upDataUi()
        {
            if (progressBar1.Value != 100000)
            {
                progressBar1.Value = progressBar1.Value + 10;
                label1.Text = progressBar1.Value.ToString();
            }
            else
            {
                t.Abort();
                t.Join();
                button1.Enabled = true;
                button2.Enabled = false;
            }

        }
     
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            t.Abort();
            t.Join();
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.