Two of the Microsoft. Net Remoting Series Tutorials: Marshal, disconnect and lifecycle and tracking services _ self-study Process

Source: Internet
Author: User
Tags constructor garbage collection

The activation of a remote object

There are three modes of activation in remoting, and the general implementation is done through static methods of the RemotingServices class. The work process is actually registering the remote object in the channel. Because remoting does not provide a corresponding unregister method to unregister remote objects, Microsoft recommends using marshal (generally translated to group) and disconnect pairing if you need to register/unregister a specified object. As I've mentioned in the Net Remoting basics: The Marshal () method converts a MarshalByRefObject class object into a ObjRef class object that stores all the relevant information needed to store a build agent to communicate with a remote object. This allows the instance to be serialized so that it can be transferred between the application domains and over the network, and the client will be able to invoke it. The disconnect () method interrupts the specific instance object from the channel.

Based on the above instructions, the Marshal () method groups the remote objects by reference (MARSHAL-BY-REFERENCE,MBR) and places the object's proxy information in the channel. The client can be obtained by Activator.GetObject (). If the user wants to unregister the object, by calling the disconnect () method. So does this approach have life-cycle management for grouped remote objects? This is the problem to be described in this article.

Second, life cycle

In the CLR, the framework provides a GC (garbage collector) to manage the lifecycle of objects in memory. Similarly,. Net Remoting uses a distributed garbage collection that manages the lifecycle of a remote object based on the form of a lease.

Early DCOM's management of object lifecycle is to determine when objects should be garbage collected by pinging and reference counting. However, the network traffic caused by Ping is a painful burden on the performance of distributed applications, which greatly affects the overall performance of distributed processing. The. Net Remoting introduces a lease manager for each application domain, singleton for each server side, Or a remote object that is activated by each client holds a reference to the leased object. (Note: For server-side-activated SingleCall, because it is stateless, for each activated remote object, the CLR's GC originates from the dynamic collection, so there is no lifecycle management for the remote object activated by SingleCall mode.) )

1. Lease

A lease is an object that encapsulates a timespan value to manage the lifetime of a remote object. The ILease interface that defines the lease functionality is provided in the. Net Remoting. When remoting activates a remote object through singleton mode or client activation mode, the leased object invokes the InitializeLifetimeService method inherited from System.MarshalByRefObject and requests a lease from the object.

The ILease interface defines the properties for the lifecycle, all of which are timespan values. As follows:

Initialleasetime: Initialize the valid time, the default value is 300 seconds, if 0, the expression never expires;
RenewOnCallTime: The lease update time when a method is invoked for a remote object, with a default value of 120 seconds;
SponsorshipTimeout: Timeout value, notify sponsor (initiator) after the lease expires, remoting will wait for the time, the default is 120 seconds;
CurrentLeaseTime: The current lease time, when first acquired, is the Initializeleasetime value.

The remoting remote object inherits the InitializeLifetimeService method by default because it inherits MarshalByRefObject, so the associated property of the lease is the default value. If you want to change these settings, you can override the method in the remote object. For example:

public override Object InitializeLifetimeService ()
{
 ilease lease = (ilease) base. InitializeLifetimeService ();
 if (lease. CurrentState = = leasestate.initial)
 {
 lease. Initialleasetime = timespan.fromminutes (1);
 Lease. RenewOnCallTime = Timespan.fromseconds (a);
 }
 return lease; 
}

You can also ignore this method to change the lease period of an object to infinity:

public override Object InitializeLifetimeService ()
{return
 null;
}

2. Leasing Manager

If the previous lease is primarily applied to each specific remote object, then the lease manager is a server-side manager dedicated to managing the lifecycle of the remote object. It maintains a system.hashtable member that maps the lease to a System.DateTime instance to indicate when each lease should expire. Remoting uses polling to wake up the lease manager for a certain amount of time to check whether each lease expires. The default is to wake up every 10 seconds. The polling interval can be configured, such as setting the polling interval to 5 minutes:

Lifetimeservice.leasemanagerpolltime = System.TimeSpan.FromMinutes (5);

We can also set the properties of a remote object lease in the lease manager, such as changing the initial valid time of a remote object to permanent validity:

Lifetimeservices.leasetime = TimeSpan.Zero;

We can also set the lifecycle through a configuration file, such as:

<configuration>
 <system.runtime.remoting>
 <application name = "Simpleserver" >
  < Lifetime Leasetime = "0" sponsorshiptimeout = "1M" renewoncalltime = "1M" polltime = "30S"/> </application>
   </system.runtime.remoting>
</configuration>

Note: The polltime in the configuration file is leasemanagerpolltime the polling interval for the lease manager described above.

The lease manager's settings for the lifecycle are for all remote objects on the server. When we set the leased property through the configuration file or the lease manager, all the remote object's lifecycle follows this setting, unless we change the configuration for the specified remote object by overriding the InitializeLifetimeService method. That is, a remote object has a higher lease configuration priority than a server-side configuration.

3. Promoter (Sponsor)

The initiator is for the client. The remote object is the object that the initiator wants to lease, the initiator can sign the lease with the server, and stipulate the lease time. Once expired, the promoter can also renew the lease, like the real life of the lease, landlord, tenant relationship.

In. Net The Clientsponsor class is defined in the System.Runtime.Remoting.Lifetime namespace in the framework, which inherits the System.MarshalByRefObject and implements the ISponsor interface. Clientsponsor the properties and methods of the class, you can refer to MSDN.

To use the initiator mechanism, a client must create an instance of the Clientsponsor class. The related methods, such as the Register () or renewal () method, are then invoked to register the remote object or extend the lifecycle. Such as:

Remotingobject obj = new Remotingobject ();
Clientsponsor sponsor = new Clientsponsor ();
Sponsor. Renewaltime = Timespan.fromminutes (2);
Sponsor. Register (obj);

The renewal time can also be set directly in the Clientsponsor constructor, such as:

Clientsponsor sponsor = new Clientsponsor (Timespan.fromminutes (2));
Sponsor. Register (obj);

We can also write our own sponsor to manage the initiator mechanism, which must inherit clientsponsor and implement the ISponsor interface.

Third, tracking service

As mentioned earlier, we want to determine whether there is a lifecycle management for grouping remote objects through Marshal. In remoting, you can monitor the marshalling process of MBR objects through a tracking service program.

We can create a simple tracking handler that implements the interface ITrackingHandler. The interface ITrackingHandler defines 3 methods, MarshalObject, Unmarshalobject, and Disconnectedobject. When a remote object is grouped, decompressed, and disconnected, the corresponding method is invoked. The following is the code for the trace processing class:

public class Mytracking:itrackinghandler
{public
 mytracking ()
 {
 ///
 TODO: Add constructor logic here
 //
 }

 public void Marshaledobject (Object obj,objref or)
 {
 Console.WriteLine ();
 Console.WriteLine ("Object" + obj.) Tostring () + "is marshaled at" + DateTime.Now.ToShortTimeString ());
 }

 public void Unmarshaledobject (Object obj,objref or)
 {
 Console.WriteLine ();
 Console.WriteLine ("Object" + obj.) Tostring () + "is unmarshaled at" + DateTime.Now.ToShortTimeString ());
 }

 public void Disconnectedobject (object obj)
 {
 Console.WriteLine (obj. ToString () + "is disconnected at" + DateTime.Now.ToShortTimeString ());
 }


It then creates an instance of the trace processing class on the server side and registers the tracking service:
Trackingservices.registertrackinghandler (New mytracking ());

Four, test

1, establish two remote objects, and rewrite the InitializeLifetimeService method:

Object one: AppService1
Initial life cycle: 1 minutes

public class Appservice1:marshalbyrefobject
{public
 void Printstring (string contents)
 {
 Console.WriteLine (contents); 
 }

 public override Object InitializeLifetimeService ()
 {
 ilease lease = (ilease) base. InitializeLifetimeService ();
 if (lease. CurrentState = = leasestate.initial)
 {
  lease. Initialleasetime = timespan.fromminutes (1);
  Lease. RenewOnCallTime = Timespan.fromseconds (a);
 }
 return lease
 }
}

Object two: AppService2
Initial life cycle: 3 minutes

public class Appservice2:marshalbyrefobject
{public
 void Printstring (string contents)
 {
 Console.WriteLine (contents); 
 }

 public override Object InitializeLifetimeService ()
 {
 ilease lease = (ilease) base. InitializeLifetimeService ();
 if (lease. CurrentState = = leasestate.initial)
 {
  lease. Initialleasetime = Timespan.fromminutes (3);
  Lease. RenewOnCallTime = Timespan.fromseconds (+);
 }
 return lease
 }
}

For simplicity, the methods for two objects are the same.

2, server-side

(1) First set up the monitoring and processing class as above;

(2) Registered channel:

TcpChannel channel = new TcpChannel (8080);
ChannelServices.RegisterChannel (channel);

(3) Set the lease manager's initial lease time to unlimited:

Lifetimeservices.leasetime = TimeSpan.Zero;

(4) Create an instance of the trace processing class and register the tracking service:

Trackingservices.registertrackinghandler (New mytracking ());

(5) Grouping of two remote objects:

Serveras.appservice1 Service1 = new Serveras1.appservice1 ();
ObjRef objRef1 = Remotingservices.marshal ((MarshalByRefObject) Service1, "AppService1");

Serveras.appservice2 Service2 = new Serveras1.appservice2 ();
ObjRef ObjRef2 = Remotingservices.marshal ((MarshalByRefObject) Service2, "AppService2");

(6) Keep the server side running:

Console.WriteLine ("Remoting service starts, press exit ..."); 
Console.ReadLine ();

3. Client

Two remote objects are obtained by Activator.GetObject () and their method printstring is called. Code slightly.

4, run the test:

Running the server side and the client, because the monitor will monitor the grouping process of the remote object, the remote object is shown to have been marshal at the start of the operation:

Then the client invokes the Printstring method of the two remote objects, and the server side accepts the string:

A minute later, a remote object is automatically disconnect:

At this point, if the client wants to invoke a remote object, it throws a RemotingException exception;

Another minute later, the remote object Two was disconnect:

The user can also test whether the renewoncalltime time is correct based on this code. In other words, when an object is not disconnect, the object is invoked, from the moment the object is invoked, its lifecycle is no longer the original valid time value (Initialleasetime) that was originally set, but rather the lease update time value (RenewOnCallTime). In addition, if the two remote objects do not override the InitializeLifetimeService method, the lifecycle should be the value set by the lease manager, which is permanently valid (set to 0). Then these two objects will not be automatically disconnect unless we explicitly specify a connection to close it. Of course, if we explicitly close the connection, the tracker will still monitor its changes and then show it.

V. Conclusion

Through our testing, the conclusion is already very obvious. Objects that are grouped by Marshal are controlled by the lease life cycle. Note that the object is disconnect, not that the object is collected by GC, but that the associated agent information that is saved in the channel is disconnected and the object itself still exists on the server side.

So we provide services through the remoting, according to the actual situation to specify the life cycle of the remote object, if not specified, the default setting for remoting. To make all remote objects permanent, you can set the initial effective time to 0 through the configuration file or the lease manager.

The above is. Net Remoting marshal, disconnect and life cycle and tracking all the content, I hope to give you a reference, but also hope that we support cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.