摘自MSDN
远程对象可能必须执行大量耗时的任务,而且在调用处于进行中时阻塞客户端是不明智的举措。此示例演示如何进行异步调用。
//share.cs ( csc /debug /target:library share.cs ------> share.dll )
using System;
namespace RemotingSamples
{
public class HelloServer : MarshalByRefObject
{
public HelloServer()
{
Console.WriteLine("HelloServer 已激活");
}
public String HelloMethod(String name)
{
Console.WriteLine("Hello.HelloMethod : {0}", name);
return "您好," + name;
}
}
}
//server.cs csc /debug /r:share.dll server.cs ---------->server.exe
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace RemotingSamples {
public class Sample {
public static int Main(string [] args) {
TcpChannel chan = new TcpChannel(8085);
ChannelServices.RegisterChannel(chan);
RemotingConfiguration.RegisterWellKnownServiceType(Type.GetType("RemotingSamples.HelloServer,share"), "SayHello", WellKnownObjectMode.SingleCall);
System.Console.WriteLine("点击 <enter> 退出...");
System.Console.ReadLine();
return 0;
}
}
}
//client.cs csc /debug /r:share.dll client.cs ---------->client.exe
using System;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace RemotingSamples {
public class Client {
public static ManualResetEvent e;
//当编译器遇到该声明时,它自动生成类 MyDelegate,并将 BeginInvoke 和 EndInvoke 方法添加到该委托中,该委托映射到公共语言运行库中某处的本机调用。
public delegate String MyDelegate(String name);
public static int Main(string [] args)
{
e = new ManualResetEvent(false);
TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan);
HelloServer obj = (HelloServer)Activator.GetObject(typeof(RemotingSamples.HelloServer), "tcp://localhost:8085/SayHello");
if (obj == null) System.Console.WriteLine("未找到服务器");
else {
AsyncCallback cb = new AsyncCallback(Client.MyCallBack);
MyDelegate d = new MyDelegate(obj.HelloMethod);
IAsyncResult ar = d.BeginInvoke("Caveman", cb, null);
}
e.WaitOne();
return 0;
}
//下列是创建接收调用结果的回调函数的代码。请注意回调是如何将 IAsyncResult 类型的对象声明为回调函数的参数的。
//调用完成后,框架确保调用的结果放置在结果对象内,然后将回调调用回客户端,将结果对象转发给客户端。
//若要检索调用的结果,请从 AsyncResult 解压缩委托,然后调用 EndInvoke。
//下面的代码示例演示对远程对象调用 HelloMethod。
public static void MyCallBack(IAsyncResult ar)
{
MyDelegate d = (MyDelegate)((AsyncResult)ar).AsyncDelegate;
Console.WriteLine(d.EndInvoke(ar));
e.Set();
}
}
}