LP on .NET

August 11, 2009

Keeping Remoting Objects Alive

Filed under: .NET,C#,Software Development — Larry Parker @ 9:15 pm

I’m currently writing a test utility to simulate multiple clients hitting a server.  There’s a simple UI that shows what’s going on, but the interesting and useful part are the client objects all running side-by-side without interfering with each other.

This is accomplished by running each client in its own application domain.  When the user initiates a client action from the UI, remoting is used to communicate with the client object in the appropriate app domain.

Everything was working great, and I was pleased with my simulator.  It’s certainly easier to run (and debug!) 10 simulators in a single test utility than having to fire up 10 separate instances of the utility app.

However, after a few minutes when I again initiated a client action from my UI, I got the following dreadful error:

RemotingException

After staring at this for a few seconds, I recalled reading the chapter on app domains in the book C# 3.0 in a Nutshell.  The problem is that remoting objects are leased, and if a leasing interval is left unspecified, the .NET runtime drops the object after about 5 minutes.

One solution is to have your remoting object (i.e. the object that descends from MarshalByRefObject) override the InitializeLifetimeService method and return null.  This tells the CLR to keep the object around for as long as the consumer needs it.

Here’s what the code looks like:

public class MyTestClient : MarshalByRefObject, IMyTestClient
{
    public override object InitializeLifetimeService()
    {
        // Tell the runtime to keep the object around
        return null;
    }
    // etc.

There are other ways to better control the object’s lease, but for my purposes this works great since the consumer of the remoting objects are in the default app domain and are alive for the duration of the utility.

I’m sure there are better discussions of this on MSDN and blogs, but if you encounter the above error, this is one way to solve it.

Hope this helps.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: