using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Serialization.Formatters;
namespace RemoteServer
{
class MyServer
{
[STAThread]
static void Main(string[] args)
{
RemotingConfiguration.ApplicationName="RemoteObject.MyObject";
RemotingConfiguration.RegisterActivatedServiceType(typeof(RemoteObject.MyObject));
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
BinaryClientFormatterSinkProvider clientProvider = new BinaryClientFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary props = new Hashtable();
props["port"]=8888;
TcpChannel channel = new TcpChannel(props,clientProvider,serverProvider);
ChannelServices.RegisterChannel(channel);
Console.ReadLine();
}
}
}
using System;
namespace RemoteObject
{
[Serializable]
public class MyEventArgs:EventArgs
{
private int _rate;
private string _ip;
public int Rate
{
get
{
return _rate;
}
}
public string IP
{
get
{
return _ip;
}
}
public MyEventArgs(int rate,string ip)
{
this._rate=rate;
this._ip=ip;
}
}
public class MyObject:MarshalByRefObject
{
public delegate void MyEventHandler(object sender,MyEventArgs e);
public event MyEventHandler MyEvent;
public string tmp;
public int ALongTimeMethod(int a,int b,int time,string ip)
{
Console.WriteLine("来自"+ip+"的异步方法开始");
for(int i=1;i<=10;i++)
{
System.Threading.Thread.Sleep(time);
Console.WriteLine("来自"+ip+"的异步方法完成了"+i*10+"%");
OnMyEvent(new MyEventArgs(i,ip));
}
Console.WriteLine("来自"+ip+"的异步方法结束");
return a+b;
}
protected void OnMyEvent(MyEventArgs e)
{
if (MyEvent!=null)
{
foreach(Delegate d in MyEvent.GetInvocationList())
{
try
{
((MyEventHandler)d)(this,e);
}
catch
{
MyEvent-=(MyEventHandler)d;
}
}
}
}
}
public class EventClass:MarshalByRefObject
{
public void MyEvent(object sender,MyEventArgs e)
{
if(((MyObject)sender).tmp==e.IP)
Console.WriteLine("异步方法完成了"+e.Rate*10+"%");
}
}
}