日期:2014-05-18 浏览次数:20912 次
using System;
using System.Threading;
namespace Cmpxx
{
public delegate void ExampleCallback(int lineCount);
public class ThreadArgState
{
private string boilerplate = "";
private int value = 0;
private event ExampleCallback callback = null;
public ThreadArgState(string text, int number,ExampleCallback callbackDelegate)
{
boilerplate = text;
value = number;
callback = callbackDelegate;
}
public void ThreadProc()
{
Console.WriteLine(boilerplate, value);
Thread.Sleep(5000);
if (callback != null)
{
//触发事件
callback(20);
}
}
}
public class Example
{
public static void SCMain()
{
//主函数执行
ThreadArgState tws = new ThreadArgState("This report displays the number {0}.", 422, new ExampleCallback(ResultCallback));
Thread t = new Thread(new ThreadStart(tws.ThreadProc));
t.Start();
Console.WriteLine("Main thread does some work, then waits.");
t.Join(); //等待线程处理完毕后才执行后面的程序,把他注释掉在看运行结果就明白了
Console.WriteLine("Independent task has completed; main thread ends.");
}
public static void ResultCallback(int lineCount)
{
Console.WriteLine("Independent task printed {0} lines.", lineCount);
}
}
}