您的位置:首页 > 其它

一个简单的多线程例子

2012-02-25 21:38 281 查看
本代码来自 http://apps.hi.baidu.com/share/detail/5571960

这段代码在我看来,只是通过定义一个线程.去改变一个文本框的值.实际上还只是做了一件事情而已. 并不是我要做的那种一边后台上传文件, 一边界面上的进度条还在滚动的效果.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
int i;
private Thread thread1;
delegate void set_Text(string s);
set_Text Set_Text; //定义委托

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "100";
Set_Text = new set_Text(set_lableText); //实例化
}

private void button1_Click(object sender, EventArgs e)
{
thread1 = new Thread(new ThreadStart(run));
thread1.Start();
}

private void run()
{
for (int i = 0; i < 101; i++)
{
label1.Invoke(Set_Text, new object[] { i.ToString() }); //通过调用委托,来改变lable1的值
Thread.Sleep(1000); //线程休眠时间,单位是ms
}
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (thread1.IsAlive)
{
thread1.Abort();
}
}

private void set_lableText(string s)
{
label1.Text = s;
}

private void timer1_Tick(object sender, EventArgs e)
{
i++;
if (i > 100)
{
timer1.Stop();
}
label1.Text = i.ToString();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: