Java中使用接口的方式,实现方法的回调机制。而在.NET里,我们通过代理,能够很轻松的实现方法的回调。
class Class1
{
[STAThread]
static void Main(string[] args)
{
Class1 c = new Class1();
ThreadWrapper tw = new ThreadWrapper(new Callback(c.PrintResult), 100);
// 线程开始
tw.Start();
Console.ReadLine();
}
// 打印结果,用于回调
public void PrintResult(int result)
{
Console.WriteLine("Result: " + result.ToString());
}
}
// 回调代理
public delegate void Callback(int n);
class ThreadWrapper
{
public readonly Thread mThread;
private Callback callback;
private int n;
// 参数1:用于回调的代理
// 参数2:需要计算的值
public ThreadWrapper(Callback callback, int arg)
{
this.callback = callback;
ThreadStart myThreadDelegate = new ThreadStart(this.Run);
this.mThread = new Thread(myThreadDelegate);
this.n = arg;
}
// 线程的对外接口
public void Start()
{
this.mThread.Start();
}
// 需要在线程里调用的方法
public void Run()
{
int result = this.Caculate(this.n);
callback(result);
}
{
return n*100;
}
}