技术开发 频道

一步一步学Remoting:异步操作


【IT168技术文档】

  如果你还不知道什么是异步也不要紧,我们还是来看实例,通过实例来理解才是最深刻的。
  在Remoting中,我们可以使用以下几种异步的方式: 
  1、普通异步
  2、回调异步
  3、单向异步
  一个一个来说,首先我们这么修改我们的远程对象:

public int ALongTimeMethod(int a,int b,int time) { Console.WriteLine("异步方法开始"); System.Threading.Thread.Sleep(time); Console.WriteLine("异步方法结束"); return a+b; }
  这个方法传入2个参数,返回2个参数和表示方法执行成功,方法需要time毫秒的执行时间,这是一个长时间的方法。
  如果方法我们通过异步远程调用,这里需要注意到这个方法输出的行是在服务器端输出的而不是客户端。因此,为了测试简单,我们还是在采用本地对象,在实现异步前我们先来看看同步的调用方法,为什么说这是一种阻塞?因为我们调用了方法主线程就在等待了,看看测试:
DateTime dt=DateTime.Now; RemoteObject.MyObject app=new RemoteObject.MyObject(); Console.WriteLine(app.ALongTimeMethod(1,2,1000)); Method(); Console.WriteLine("用了"+((TimeSpan)(DateTime.Now-dt)).TotalSeconds+""); Console.ReadLine();
  假设method方法是主线程的方法,需要3秒的时间:
private static void Method() { Console.WriteLine("主线程方法开始"); System.Threading.Thread.Sleep(3000); Console.WriteLine("主线程方法结束"); }
  1、普通异步:
  首先在main方法前面加上委托,签名和返回类型和异步方法一致。
private delegate int MyDelegate(int a,int b,int time); main方法里面这么写: DateTime dt=DateTime.Now; RemoteObject.MyObject app=new RemoteObject.MyObject(); MyDelegate md=new MyDelegate(app.ALongTimeMethod); IAsyncResult Iar=md.BeginInvoke(1,2,1000,null,null); Method(); if(!Iar.IsCompleted) { Iar.AsyncWaitHandle.WaitOne(); } else { Console.WriteLine("结果是"+md.EndInvoke(Iar)); } Console.WriteLine("用了"+((TimeSpan)(DateTime.Now-dt)).TotalSeconds+""); Console.ReadLine();
0
相关文章