.NET Remoting 经典远程回调模型(二)

         为了简化客户端代码,可以将远程对象实现为异步操作的形式。

         那么,当异步操作完成时如何通知客户端呢??

         这里,来说下第二种,使用定制委托实现回调。

接着上个SimpleMath类说,

public class SimpleMath:MarshalByRefObject

{

     private delegate int opDelegate(int n1, int n2);

     public delegate void ClientCallbackDelegate(int result);

     public int Add(int n1, int n2)

   {

        return n1+n2;

    }

     public void AsyncAdd(int n1,int n2,ClientCallbackDelegate callback)

    {

          opDelegate op=  new opDelegate(Add);

           op.BeginInvoke(n1,n2,new AsycCallback(DoClientCallback),callback);

      }

     private void DoClientCallback(IAsyncResult ar)

     {

          AsyncResult asyncResult=(AsyncResult)ar;

          opDelegate  op= (opDelegate)asyncResult.AsyncDelegate;

         int result=op.EndInvoke(ar);

         ClientCallbackDelegate callback=(ClientCallbackDelegate)ar.AsyncState;

         callback(result);

      }

}

 

//以下这个类是重点:

//必须把其元数据部署到服务器端;

//其实现要在客户端。

//此时,原来的客户端成了服务端,服务端成了客户端。

public class SimpleMathResult:MarshalByRefObject

{

      public void MathCallback(int result)

       {

             Console.WriteLine(result.tostring());

         }

}

 

class ClientMain

{

     static void Main(string[] args)

     {

            RemotingConfguration.Configure("MathClient.exe.config");

           SimpleMath math= new SimpleMath();

           SimpleMathResult mathResult= new SimpleMathResult();

           math.AsyncAdd(5,2,new SimpleMath.ClientCallbackDelegate(mathResult.MathCallback));

      }

}

其实重点还是怎样传递委托实例,去调用我们对应的方法,这点很重要。

posted on 2009-12-04 20:55  Mayvar  阅读(362)  评论(0编辑  收藏  举报

导航