使用Thread包装类进行多线程操作

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);
  }

  private int Caculate(int n)
  {
      return n*100;
  }
 }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值