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

WinForm多线程+委托防止界面卡死

时间:2014-05-19 09:47:53      阅读:340      评论:0      收藏:0      [点我收藏+]

标签:winform   style   blog   class   code   c   

1、当有大量数据需要计算、显示在界面或者调用sleep函数时,容易导致界面卡死,可以采用多线程加委托的方法解决

 

bubuko.com,布布扣
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();
        }
    }
}
bubuko.com,布布扣

 

WinForm多线程+委托防止界面卡死,布布扣,bubuko.com

WinForm多线程+委托防止界面卡死

标签:winform   style   blog   class   code   c   

原文地址:http://www.cnblogs.com/bdzwater/p/3731904.html

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