c# winform 实现多线程

时间:2022-09-12 15:12:26

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