单独的类文件
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ThreadTest { public class MoreTime { public delegate void InvokeOtherThead(int i); public InvokeOtherThead MainThread; public void WaitMoreTime() { for (int i= 0 ; i<20;i++) { Thread.Sleep(2000); MainThread(i); } } } }
启动线程的代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ThreadTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MoreTime mt = new MoreTime(); mt.MainThread = new MoreTime.InvokeOtherThead(AddToList); ThreadStart start = new ThreadStart(mt.WaitMoreTime); Thread thread = new Thread(start); thread.Start(); } public void AddToList(int i) { if (this.listBox1.InvokeRequired) { MoreTime mt = new MoreTime(); mt.MainThread = new MoreTime.InvokeOtherThead(AddToList); this.Invoke(mt.MainThread, new object[] { i}); } else { listBox1.Items.Add(i.ToString()); } } } }