今天就先谈谈Remoting序列化的问题:首先,Remoting序列化是为了方便网络传输,把远程对象转化为网络可传输的形式。Remoting序列化可以实现多种形式:序列化为xml、序列化为二进制等等。当然使用序列化需要添加一个标记【Serializable】,而且可以用SerializableAttribute,或是实现ISerializable接口。下面放个序列化的代码Demo:
1: [Serializable]
2: public class SumOf
3: {
4: public SumOf()
5: {
6: }
7:
8: public DecimalList Members = new DecimalList();
9:
10: public decimal Sum,Avg;
11:
12: public void Calculate()
13: {
14: this.Sum = 0;
15: foreach (decimal m in Members)
16: {
17: Sum += m;
18: }
19: this.Avg = Sum / Members.Count;
20:
21: }
22:
23: }
24: [Serializable]
25: public class DecimalList : List<decimal>
26: {
27: }
1.对象的生命周期
我们先来认识一下什么是对象,对象就是内存里的数据结构。先说客户机检测服务器是否可用,那我们就要验证远程对象是否还存在。这个很简单,我们只要调用远程对象,如果远程对象不可用,会出现异常,那说明服务器不可用。接着说服务器检测客户机是否可用,使用垃圾回收机制验证,只对Singleton对象和客户端激活对象有效。
2.什么是租约
租约是在服务器记录的一个时间,如果超过这个时间,对象会被回收。
3、续约:为了让对象继续存在就必须使用续约
(1)隐式续约:每次调用远程对象上的方法的时候自动进行。
(2)显示续约:使用ILease.Renew()方法实现。
(3)发起租约:租约管理者自动续约。ILease.Register()
租约的配置:InitialLeaseTime 租约时间,默认值 300 。RenewOnCallTime检查时间 默认值120 。SponsorshipTimeout过期时间 默认值120。LeaseManagerPollTime租约管理者临行时间 默认值10
如何显示租约信息:
1: ILease lease = (ILease)obj.GetLifetimeService();
2:
3: if (lease != null)
4: {
5: Console.WriteLine("Lease Configuration:");
6: Console.WriteLine("InitialLeaseTime: " +
7: lease.InitialLeaseTime);
8: Console.WriteLine("RenewOnCallTime: " +
9: lease.RenewOnCallTime);
10: Console.WriteLine("SponsorshipTimeout: " +
11: lease.SponsorshipTimeout);
12: Console.WriteLine(lease.CurrentLeaseTime);
13: }
如何配置租约信息:
1代码方式
1: public override Object InitializeLifetimeService()
2: {
3:
4: ILease lease = (ILease)base.InitializeLifetimeService();
5: // Normally, the initial lease time would be much longer.
6: // It is shortened here for demonstration purposes.
7: if (lease.CurrentState == LeaseState.Initial)
8: {
9: lease.InitialLeaseTime = TimeSpan.FromSeconds(3);
10: lease.SponsorshipTimeout = TimeSpan.FromSeconds(10);
11: lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
12: }
13: return lease;
14: }
2配置文件方式1: <lifetime
2: leaseTime="7M"
3: sponsorshipTimeout="7M"
4: renewOnCallTime="7M"
5: />
本文来自零末的博客园文章《Remoting学习历程(2)》
【编辑推荐】