using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 多线程_委托
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//3.2在窗体加载的时候用‘写的方法DoShoumsgintextbox()’来实例化委托
Control.CheckForIllegalCrossThreadCalls = false;
dgshoumsgintextbox = new DGDoshoumsgintextbox(DoShoumsgintextbox);
DGaddtext dgaddtext = new DGaddtext(Addtext);
}
//4要调用的方法
private void AddString()
{
DateTime beginTime = DateTime.Now;
for (int i = 0; i < 100000; i++)
{
//txtNum1.Text = i.ToString();不能用这个方法给txtnum赋值
///必须用control的invoke方法
this.Invoke(dgshoumsgintextbox, i.ToString());
}
DateTime endTime = DateTime.Now;
TimeSpan ts = endTime.Subtract(beginTime);
MessageBox.Show(ts.Milliseconds.ToString());
}
private void button1_Click(object sender, EventArgs e)
{
Thread th = new Thread(AddString);
th.Start();
}
//1.申明方法
void DoShoumsgintextbox(string s)
{
txtNum1.Text = s;
}
//2申明委托
delegate void DGDoshoumsgintextbox(string dgs);
//3.1实例化委托1
DGDoshoumsgintextbox dgshoumsgintextbox = null;
private void button2_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ParameterizedThreadStart(Addtext));
Myclass myclass = new Myclass();
myclass.a = "这个你能理解吗??";
myclass.b = "其实只要认真看就可以看懂的啦";
th.Start(myclass);
}
void Addtext(object obj)
{
Myclass mc = obj as Myclass;
txtNum1.AppendText(mc.a+mc.b);
}
delegate void DGaddtext(object objt);
}
}
类
public class Myclass
{
public string a;
public string b;
}