WinForm多線程+委託防止界面卡死

一、當有大量數據須要計算、顯示在界面或者調用sleep函數時,容易致使界面卡死,能夠採用多線程加委託的方法解決多線程

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;


namespace WindowsFormTest{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        Thread drawThread = null;            
        delegate void drawDelegate(int i);

        //開啓子線程
        private void btnTest_Click(object sender, EventArgs e)
        {
            closeThread();

            drawThread = new Thread(new ThreadStart(draw));
            drawThread.IsBackground = true;
            drawThread.Start();
        }

        //draw子線程,循環調用test函數,而且等待一會
        private void draw()
        {
            try
            {
                for (int i = 0; i < 100000000; i++)
                {
                    test(i);
                    Thread.Sleep(100);
                }
            }
            catch (System.Exception e1)
            {
                return;
            }

            closeThread();
        }

        //test函數,向textBox中添加數據
        private void test(int i)
        {
            if (textBox1.InvokeRequired)
            {
                drawDelegate d = new drawDelegate(test);
                Invoke(d, new object[] {i });
            } 
            else
            {
                textBox1.AppendText(i.ToString()+"\r\n");
            }
        }      

        //結束子線程
        private void closeThread()
        {
            if (drawThread != null)
            {
                if (drawThread.IsAlive)
                {
                    drawThread.Abort();
                }
            }
        }
        
        //窗體關閉時,關閉子線程
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            closeThread();
        }
    }
}
相關文章
相關標籤/搜索