1. 程式人生 > >c# winform 實現多執行緒

c# winform 實現多執行緒

UI介面就一個label一個button,

點選button讓label的值改變

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;
using System.Text.RegularExpressions;
using System.Net;
namespace TestThread
{

    
   
        public partial class Form1 : Form
        {
            public delegate void treeinvoke(int i);
            int num1 = 0;
            int num2 = 10000;
            public Form1()
            {
                InitializeComponent();
            }
            private void button1_Click(object sender, EventArgs e)
            {
                Console.WriteLine("AAA");


                for (int i = 0; i < 5000; i++)
                {
                    ThreadPool.QueueUserWorkItem(startupdate, i);
                }

                Console.WriteLine("BBB");
            }
            private delegate void updateui();
            private void TimeEvent(object source, System.Timers.ElapsedEventArgs e)
            {
                this.BeginInvoke(new updateui(upui));
            }
            private void upui()
            {
                label1.Text = num1.ToString() + "/" + num2.ToString();
            }
            private void startupdate(object c)
            {
                System.DateTime dt = DateTime.Now;

                Console.WriteLine("CCC");
                UpdateTreeView(int.Parse(c.ToString()));
                Console.WriteLine("DDD");
            }

            private void UpdateTreeView(int j)
            {
                //反正這裡執行耗時間操作Start
                try
                {
                    string strPageData = GetHttp("http://news.163.com/rank/", Encoding.GetEncoding("GB2312"));
                    this.BeginInvoke(new updateui(upui));//這裡更新UI
                    Console.WriteLine(j.ToString());
                    num1 = j;
                }
                catch (Exception ex)
                {

                }
                //反正這裡執行耗時間操作End
            }
            public static string GetHttp(string url, Encoding encode)
            {
                string strResult;
                try
                {
                    WebClient client = new WebClient();
                    client.Encoding = encode;
                    strResult = client.DownloadString(url);
                }
                catch
                {
                    strResult = "";
                }
                return strResult;
            }

        }
    }


引用 http://bbs.csdn.net/topics/390577421