关于线程的参数(2.0)、“返回值”、及线程的中止
1.线程的参数:
有时候会想向辅助线程传递些信息,这里需要用到ParameterizedThreadStart 委托
示例:
private void btRunThread_Click(object sender, EventArgs e)
{
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com)Thread t = new Thread(new ParameterizedThreadStart(this.ThreadRun));
t.Start(100);
}
private void ThreadRun(object o)
{
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com)this.lbCompleted.Invoke((MethodInvoker)delegate { this.lbCompleted.Text = System.Convert.ToString(o); });
}
2.通过代理可以大致实现类似功能,示例:
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com)class Program
{
static void Main(string[] args)
{
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com)ThreadClass tc = new ThreadClass(new MyDlg(DlgMethod));
Thread thread = new Thread(new ThreadStart(tc.ThreadRun));
Console.WriteLine("second thread start");
thread.Start();
thread.Join();
Console.WriteLine("second thread completed");
Console.Read();
}
private static void DlgMethod(int i)
{
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com)Console.WriteLine("Second Thread Result:{0}", i);
}
}
public delegate void MyDlg(int i);
class ThreadClass
{
private MyDlg myDlg;
public ThreadClass(MyDlg pDlg)
{
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com)this.myDlg = pDlg;
}
public void ThreadRun()
{
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com)int total = 0;
for (int i = 0; i < 100; i++)[next]
{
total += i;
}
if (myDlg != null)
{
myDlg(total);
}
}