MarshalByRefObject Class
 

Enables access to objects across application domain boundaries in applications that support remoting.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

SystemObject
  SystemMarshalByRefObject
     Microsoft.Build.UtilitiesAppDomainIsolatedTask
     Microsoft.Build.UtilitiesTaskItem
     Microsoft.Build.UtilitiesTaskLoggingHelper
     Microsoft.Win32RegistryKey
     System.AddIn.PipelineContractBase
     SystemAppDomain
     SystemAppDomainManager
     System.ComponentModelComponent
     SystemContextBoundObject
     System.Data.CommonDataColumnMapping
     System.Data.CommonDataColumnMappingCollection
     System.Data.CommonDataTableMapping
     System.Data.CommonDataTableMappingCollection
     System.Data.CommonDbDataReader
     System.Data.CommonDbParameter
     System.Data.CommonDbParameterCollection
     System.Data.CommonDbTransaction
     System.DiagnosticsTraceListener
     System.DirectoryServicesSearchResultCollection
     System.DrawingBrush
     System.Drawing.Drawing2DCustomLineCap
     System.Drawing.Drawing2DGraphicsContainer
     System.Drawing.Drawing2DGraphicsPath
     System.Drawing.Drawing2DGraphicsPathIterator
     System.Drawing.Drawing2DGraphicsState
     System.Drawing.Drawing2DMatrix
     System.DrawingFont
     System.DrawingFontFamily
     System.DrawingGraphics
     System.DrawingIcon
     System.DrawingImage
     System.DrawingPen
     System.DrawingRegion
     System.DrawingStringFormat
     System.EnterpriseServices.InternalAssemblyLocator
     System.EnterpriseServicesRegistrationHelper
     System.IOFileSystemInfo
     System.IO.IsolatedStorageIsolatedStorage
     System.IOStream
     System.IOTextReader
     System.IOTextWriter
     System.MessagingMessageEnumerator
     System.MessagingMessageQueueEnumerator
     System.NetWebRequest
     System.NetWebResponse
     System.ReflectionAssemblyNameProxy
     System.Runtime.InteropServicesStandardOleMarshalObject
     System.Runtime.Remoting.LifetimeClientSponsor
     System.Runtime.RemotingObjectHandle
     System.Speech.Recognition.SrgsGrammarSrgsElement
     System.ThreadingRegisteredWaitHandle
     System.ThreadingTimer
     System.ThreadingWaitHandle
     System.Web.CompilationClientBuildManager
     System.Web.CompilationClientBuildManagerCallback
     System.Web.HostingAppDomainProtocolHandler
     System.Web.HostingApplicationManager
     System.Web.HostingHostingEnvironment
     System.Web.HostingISAPIRuntime
     System.Web.HostingProcessHost
     System.Web.HostingProcessHostFactoryHelper
     System.Web.HostingProcessProtocolHandler
     System.Web.HostingRecycleLimitMonitor
     System.Web.HostingRecycleLimitMonitorRecycleLimitMonitorSingleton
     System.Web.HostingVirtualFileBase
     System.Web.HostingVirtualPathProvider
     System.Windows.FormsBaseCollection
     System.Windows.FormsNativeWindow
     System.Windows.FormsNumericUpDownAccelerationCollection
     System.Windows.FormsOwnerDrawPropertyBag
     System.Windows.FormsTreeNode
     System.Windows.InteropDocObjHost
     System.Workflow.Runtime.DebugEngineDebugController

[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class MarshalByRefObject
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class MarshalByRefObject abstract 
[<AbstractClass>]
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type MarshalByRefObject = class end
<SerializableAttribute>
<ComVisibleAttribute(True)>
Public MustInherit Class MarshalByRefObject
NameDescription
System_CAPS_protmethod MarshalByRefObject

Initializes a new instance of the MarshalByRefObject class.

NameDescription
System_CAPS_pubmethod CreateObjRef

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

System_CAPS_pubmethod Equals

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethod Finalize

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_pubmethod GetHashCode

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethod GetLifetimeService

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

System_CAPS_pubmethod GetType

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethod InitializeLifetimeService

Obtains a lifetime service object to control the lifetime policy for this instance.

System_CAPS_protmethod MemberwiseClone

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_protmethod MemberwiseClone

Creates a shallow copy of the current MarshalByRefObject object.

System_CAPS_pubmethod ToString

Returns a string that represents the current object.(Inherited from Object.)

An application domain is a partition in an operating system process where one or more applications reside. Objects in the same application domain communicate directly. Objects in different application domains communicate either by transporting copies of objects across application domain boundaries, or by using a proxy to exchange messages.

MarshalByRefObject is the base class for objects that communicate across application domain boundaries by exchanging messages using a proxy. Objects that do not inherit from MarshalByRefObject are implicitly marshal by value. When a remote application references a marshal by value object, a copy of the object is passed across application domain boundaries.

MarshalByRefObject objects are accessed directly within the boundaries of the local application domain. The first time an application in a remote application domain accesses a MarshalByRefObject, a proxy is passed to the remote application. Subsequent calls on the proxy are marshaled back to the object residing in the local application domain.

Types must inherit from MarshalByRefObject when the type is used across application domain boundaries, and the state of the object must not be copied because the members of the object are not usable outside the application domain where they were created.

When you derive an object from MarshalByRefObject for use across application domain boundaries, you should not override any of its members, nor should you call its methods directly. The runtime recognizes that classes derived from MarshalByRefObject should be marshaled across app domain boundaries.

This section contains two code examples. The first code example shows how to create an instance of a class in another application domain. The second code example shows a simple class that can be used for remoting.

Example 1

The following code example shows the simplest way to execute code in another application domain. The example defines a class named Worker that inherits MarshalByRefObject, with a method that displays the name of the application domain in which it is executing. The example creates instances of Worker in the default application domain and in a new application domain.

System_CAPS_noteNote

The assembly that contains Worker must be loaded into both application domains, but it could load other assemblies that would exist only in the new application domain.

using System;
using System.Reflection;

public class Worker : MarshalByRefObject
{
    public void PrintDomain() 
    { 
        Console.WriteLine("Object is executing in AppDomain \"{0}\"",
            AppDomain.CurrentDomain.FriendlyName); 
    }
}

class Example
{
    public static void Main()
    {
        // Create an ordinary instance in the current AppDomain
        Worker localWorker = new Worker();
        localWorker.PrintDomain();

        // Create a new application domain, create an instance
        // of Worker in the application domain, and execute code
        // there.
        AppDomain ad = AppDomain.CreateDomain("New domain");
        Worker remoteWorker = (Worker) ad.CreateInstanceAndUnwrap(
            typeof(Worker).Assembly.FullName,
            "Worker");
        remoteWorker.PrintDomain();
    }
}

/* This code produces output similar to the following:

Object is executing in AppDomain "source.exe"
Object is executing in AppDomain "New domain"
 */
Imports System.Reflection

Public Class Worker
    Inherits MarshalByRefObject

    Public Sub PrintDomain() 
        Console.WriteLine("Object is executing in AppDomain ""{0}""", _
            AppDomain.CurrentDomain.FriendlyName)
    End Sub 
End Class 

Class Example

    Public Shared Sub Main() 
        ' Create an ordinary instance in the current AppDomain
        Dim localWorker As New Worker()
        localWorker.PrintDomain()

        ' Create a new application domain, create an instance
        ' of Worker in the application domain, and execute code
        ' there.
        Dim ad As AppDomain = AppDomain.CreateDomain("New domain")
        Dim remoteWorker As Worker = CType( _
            ad.CreateInstanceAndUnwrap( _
                GetType(Worker).Assembly.FullName, _
                "Worker"), _
            Worker)
        remoteWorker.PrintDomain()

    End Sub 
End Class 

' This code produces output similar to the following:
'
'Object is executing in AppDomain "source.exe"
'Object is executing in AppDomain "New domain"
using namespace System;
using namespace System::Reflection;

public ref class Worker : MarshalByRefObject
{
public:
    void PrintDomain() 
    { 
        Console::WriteLine("Object is executing in AppDomain \"{0}\"",
            AppDomain::CurrentDomain->FriendlyName); 
    }
};

void main()
{
    // Create an ordinary instance in the current AppDomain
    Worker^ localWorker = gcnew Worker();
    localWorker->PrintDomain();

    // Create a new application domain, create an instance
    // of Worker in the application domain, and execute code
    // there.
    AppDomain^ ad = AppDomain::CreateDomain("New domain");
    Worker^ remoteWorker = (Worker^) ad->CreateInstanceAndUnwrap(
        Worker::typeid->Assembly->FullName,
        "Worker");
    remoteWorker->PrintDomain();
}

/* This code produces output similar to the following:

Object is executing in AppDomain "source.exe"
Object is executing in AppDomain "New domain"
 */

Example 2

The following example demonstrates a class derived from MarshalByRefObject that is used later in remoting.

using System;
using System.Runtime.Remoting;
using System.Security.Permissions;

public class SetObjectUriForMarshalTest  {

    class TestClass : MarshalByRefObject {
    }

    [SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)] 
    public static void Main()  {

        TestClass obj = new TestClass();    

        RemotingServices.SetObjectUriForMarshal(obj, "testUri");
        RemotingServices.Marshal(obj);

        Console.WriteLine(RemotingServices.GetObjectUri(obj));
    }
}
Imports System.Runtime.Remoting
Imports System.Security.Permissions


Public Class SetObjectUriForMarshalTest

    Class TestClass
        Inherits MarshalByRefObject
    End Class

    <SecurityPermission(SecurityAction.Demand, Flags:= SecurityPermissionFlag.RemotingConfiguration )> _
    Public Shared Sub Main()
        Dim obj As TestClass = New TestClass()

        RemotingServices.SetObjectUriForMarshal(obj, "testUri")
        RemotingServices.Marshal(obj)

        Console.WriteLine(RemotingServices.GetObjectUri(obj))
    End Sub

End Class
using namespace System;
using namespace System::Runtime::Remoting;
using namespace System::Security::Permissions;

public ref class SetObjectUriForMarshalTest
{
public:
   ref class TestClass: public MarshalByRefObject{};

   [SecurityPermissionAttribute(SecurityAction::Demand, Flags=SecurityPermissionFlag::RemotingConfiguration)]   
   static void Main()
   {
      TestClass^ obj = gcnew TestClass;
      RemotingServices::SetObjectUriForMarshal( obj,  "testUri" );
      RemotingServices::Marshal(obj);
      Console::WriteLine( RemotingServices::GetObjectUri( obj ) );
   }

};
.NET Framework
Available since 1.1

Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top