C#2.0多线程跨线程访问UI
C#2.0多线程跨线程访问UI
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Collections;
namespace TestTheads
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ArrayList threads = new ArrayList();
public delegate void ChangeText(int i,int j); //定义一个委托来改变变化的数字
public delegate void setText(int ct);//定义委托来改变文字
private void button1_Click(object sender, EventArgs e)
{
Add();
}
private void Add()
{
int count = threads.Count;
if (count < 10)
{
//使用委托来改变控件的显示
this.Invoke(new setText(this.Settexts), new object[] { count });
Thread t = new Thread(new ThreadStart(Process));
t.Start();
threads.Add(t);
}
}
private void Del()
{
int count = threads.Count;
if (count > 0)
{
Thread t1 = (Thread)threads[count - 1];
if (t1.IsAlive)
{
t1.Abort();
}
threads.RemoveAt(count - 1);
lock (listView1)
{
listView1.Items.RemoveAt(count - 1);
}
}
}
private void Process()
{
//CheckForIllegalCrossThreadCalls = false;//如果使用这句话则可以不使用委托而使用非安全的方法来访问控件
int i = 1;
while (true)
{
i++;
int j = threads.IndexOf(Thread.CurrentThread);
//利用委托来执行
this.Invoke(new ChangeText(this.Display), new object[] { j,i });
Thread.Sleep(10);
}
}
//动态更改LISTVIEW
private void Display(int j,int i)
{
lock (listView1)
{
this.listView1.Items[j].SubItems[1].Text = i.ToString();
}
}
//设置LISTVIEW的值
private void Settexts(int cts)
{
lock (listView1)
{
listView1.Items.Insert(cts, new ListViewItem(new string[] { cts.ToString(), "0" }));
}
}
private void button2_Click(object sender, EventArgs e)
{
Del();
}
private void button3_Click(object sender, EventArgs e)
{
disposethead();
}
private void disposethead()
{
while (threads.Count > 0)
{
Thread t1 = (Thread)threads[0];
if (t1.IsAlive)
{
t1.Abort();
}
threads.RemoveAt(0);
lock (listView1)
{
listView1.Items.RemoveAt(0);
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
disposethead();
}
}
}