Microsoft. Net Remoting Series II

Source: Internet
Author: User

Microsoft. Net Remoting Series II 

1. Activation of remote objects

There are three activation methods in Remoting. The general implementation is through the static method of the RemotingServices class. The procedure is to register the remote object to the channel. Since Remoting does not provide the corresponding Unregister method to deregister remote objects, if you need to register/deregister a specified object, Microsoft recommends using Marshal (usually translated as grouping) and Disconnect pairs. In the Net Remoting basics article, I have mentioned that the Marshal () method is to convert the externalbyrefobject class object to an ObjRef class object, this object stores all the information required to generate a proxy to communicate with a remote object. In this way, the instance can be serialized for transmission between application domains and through the network, and the client can call it. The Disconnect () method disconnects a specific instance object from the channel.

According to the preceding instructions, the Marshal () method groups remote objects by Reference (MBR) and puts the object's proxy information into the channel. The client can obtain it through Activator. GetObject. If you want to deregister this object, call the Disconnect () method. Does this method manage the lifecycle of remote objects in a group? This is the problem described in this article.

Ii. Lifecycle

In CLR, the Framework provides GC (Garbage Collector) to manage the lifecycle of objects in memory. Similarly,. Net Remoting uses a distributed garbage collection method to manage the lifecycle of remote objects based on lease.

Early DCOM manages the object lifecycle by Using ping and reference count to determine when the object should be recycled as garbage. 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 .. Net Remoting introduces a lease manager in each application domain to store references to lease objects for SingleTon on each server or remote objects activated by each client. (Note: Because the SingleCall method activated on the server is stateless, each activated remote object is automatically recycled by clr gc, therefore, there is no lifecycle management for remote objects activated in SingleCall mode .)

1. Rent

Lease is an object that encapsulates the TimeSpan value to manage the lifetime of a remote object. The. Net Remoting interface defines the lease function. When Remoting activates a remote object in SingleTon mode or client activation mode, the rented object calls the InitializeLifetimeService method inherited from System. delealbyrefobject to request rent from the object.

The ILease interface defines the lifecycle attributes, all of which are TimeSpan values. As follows:
InitialLeaseTime: Specifies the initialization validity period. The default value is 300 seconds. If the value is 0, the initialization will never expire;
RenewOnCallTime: The lease Update time when a remote object method is called. The default value is 120 seconds;
SponsorshipTimeout: time-out value. Remoting will wait after the worker sor (initiator) is notified that the lease has expired. The default value is 120 seconds;
CurrentLeaseTime: current lease time. The value of InitializeLeaseTime is used to obtain the first lease.

The Remoting remote object inherits the delealbyrefobject method, and the default value is the InitializeLifetimeService method. If you want to change these settings, you can rewrite this method in a 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 (20 );
}
Return lease;
}

You can also ignore this method to change the lease period of an object to unlimited:
Public override object InitializeLifetimeService ()
{
Return null;
}

2. Rent a manager

If the lease is mainly applied to each specific remote object, the lease manager is the manager dedicated on the server side to manage the remote object lifecycle, which maintains a System. the Hashtable member maps the lease to System. dateTime instances indicate the expiration time of each lease. Remoting uses polling to wake up the lease manager for a certain period of time and check whether each lease has expired. The default value is to wake up every 10 seconds. The polling interval can be configured. For example, set the polling interval to 5 minutes: LifetimeService. LeaseManagerPollTime = System. TimeSpan. FromMinutes (5 );

You can also set the remote object lease attribute in the lease manager. For example, you can change the initial validity period of the remote object to permanent validity:
LifetimeServices. LeaseTime = TimeSpan. Zero;

We can also set the lifecycle through the configuration file, such:
& Lt; configuration & gt;
& Lt; system. runtime. remoting & gt;
& Lt; application name = "SimpleServer" & gt;
& Lt; lifetime leaseTime = "0" sorshiptimeout = "1 M" renewOnCallTime = "1 M" pollTime = "30 S"/& gt;
& Lt;/application & gt;
& Lt;/system. runtime. remoting & gt;
& Lt;/configuration & gt;

Note: The pollTime in the configuration file is the polling interval LeaseManagerPollTime of the lease manager mentioned above.

The lease manager sets the lifecycle for all remote objects on the server. When we set the lease attribute through the configuration file or the lease manager, the lifecycle of all remote objects follows this setting, unless we rewrite the InitializeLifetimeService method for the specified remote object, changed the configuration. That is to say, the lease configuration of remote objects has a higher priority than the server configuration.

3. Initiator)

The initiator is for the client. Remote objects are the objects to be rented by the initiator. The initiator can sign a lease with the server to specify the lease time. Once it expires, the initiator can renew the lease, just like the real-life lease contract, the relationship between the landlord and the lease.

The clienteffecsor class is defined in the. Net Framework System. Runtime. Remoting. Lifetime namespace. This class inherits System. delealbyrefobject and implements the ISponsor interface. For the attributes and methods of the clientshortsor class, refer to MSDN.

To use the initiator mechanism, the client must create an instance of the clientaggregsor class. Then, call related methods such as Register () or Renewal () to Register remote objects or extend the lifecycle. For example:
RemotingObject obj = new RemotingObject ();
Clientshortsor extends sor = new clientshortsor ();
Using sor. RenewalTime = TimeSpan. FromMinutes (2 );
Using sor. Register (obj );

The lease renewal time can also be set directly in the clientshortsor constructor, for example:
Clientshortsor extends sor = new clientshortsor (TimeSpan. FromMinutes (2 ));
Using sor. Register (obj );

You can also write the aggregsor to manage the initiator mechanism. This class must inherit the clientaggregsor and implement the ISponsor interface.

Iii. Tracking Service

As mentioned above, we need to determine whether a remote object can be managed through Marshal grouping. In Remoting, you can track the service program to monitor the MBR object grouping process.

We can create a simple tracking handler that implements the ITrackingHandler interface. The ITrackingHandler interface defines three methods: externalobject, unexternalobject, and DisconnectedObject. When a remote object is grouped, unbound, or disconnected, the corresponding method is called. The following is the code for this tracking processing class: public class MyTracking: ITrackingHandler
{
Public MyTracking ()
{
//
// TODO: add the constructor logic here
//
}

Public void export aledobject (object obj, ObjRef or)
{
Console. WriteLine ();
Console. WriteLine ("object" + obj. Tostring () + "is stored aled at" + DateTime. Now. tow.timestring ());
}

Public void UnmarshaledObject (object obj, ObjRef or)
{
Console. WriteLine ();
Console. WriteLine ("object" + obj. Tostring () + "is unmarshaled at" + DateTime. Now. tow.timestring ());
}

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

Then, the server creates an instance for the trail processing class and registers the trail service:
TrackingServices. RegisterTrackingHandler (new MyTracking ());

Iv. Test

1. Create two remote objects and override the InitializeLifetimeService method:

Object 1: AppService1
Initial lifecycle: 1 minute

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 (20 );
}
Return lease;

}
}

Object 2: AppService2
Initial lifecycle: 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 (40 );
}
Return lease;

}
}

For simplicity, the methods of both objects are the same.

2. Server Side

(1) first establish the above monitoring and processing class;

(2) Registration channel:
TcpChannel channel = new tcpchannels (8080 );
ChannelServices. RegisterChannel (channel );

(3) set the initial lease time of the lease manager to unlimited:
LifetimeServices. LeaseTime = TimeSpan. Zero;

(4) Create an instance of the trail processing class and register the trail service:
TrackingServices. RegisterTrackingHandler (new MyTracking ());

(5) group 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 running:
Console. WriteLine ("Remoting service started, press to exit ...");
Console. ReadLine ();

3. Client

Use Activator. GetObject () to obtain two remote objects and call the PrintString method. Code omitted.

4. Run the test:

Run the server and client. Because the monitoring program will monitor the grouping process of remote objects, it will show that the remote object has been Marshal at the beginning of running:

Then the client calls the PrintString method of the two remote objects, and the Server accepts the string:

One minute later, the remote object is automatically Disconnect:

In this case, if the client needs to call Remote Object 1, A RemotingException is thrown;

Another minute later, the remote object was Disconnect:

Align = "center">

You can also test whether the RenewOnCallTime is correct based on this code. That is to say, when an object has not been Disconnect and the called object is called, its life cycle is no longer the initial effective time value (InitialLeaseTime) from the moment the object is called ), instead, the lease Update Time Value (RenewOnCallTime) is used ). In addition, if the two remote objects do not override the InitializeLifetimeService method, the life cycle should be the value set by the lease manager, which is permanently valid (set to 0 ). The two objects will not be automatically Disconnect unless we explicitly specify to close the connection. Of course, if we explicitly close the connection, the tracing program will still monitor its changes and display them.

V. Conclusion

Through our tests, the conclusion is obvious. Objects grouped by Marshal are subject to the lease life cycle. Note that the Disconnect object does not mean that the object is recycled by GC, but that the agent information of the object stored in the channel is disconnected, and the object still exists on the server.

Therefore, to provide services through Remoting, we should specify the lifecycle of the remote object based on actual conditions. If this parameter is not specified, the default setting of Remoting is used. To make all remote objects permanently valid, you can set the initial validity period to 0 through the configuration file or the lease manager.

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.