MarshalByRefObject MarshalByRefObject MarshalByRefObject MarshalByRefObject Class

Definição

Permite acesso a objetos entre limites de domínio de aplicativo em aplicativos que dão suporte a comunicação remota.Enables access to objects across application domain boundaries in applications that support remoting.

public ref class MarshalByRefObject abstract
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public abstract class MarshalByRefObject
type MarshalByRefObject = class
Public MustInherit Class MarshalByRefObject
Herança
MarshalByRefObjectMarshalByRefObjectMarshalByRefObjectMarshalByRefObject
Derivado
Atributos

Exemplos

Esta seção contém dois exemplos de código.This section contains two code examples. O primeiro exemplo de código mostra como criar uma instância de uma classe em outro domínio de aplicativo.The first code example shows how to create an instance of a class in another application domain. O segundo exemplo de código mostra uma classe simples que pode ser usada para comunicação remota.The second code example shows a simple class that can be used for remoting.

Exemplo 1Example 1

O exemplo de código a seguir mostra a maneira mais simples para executar código em outro domínio de aplicativo.The following code example shows the simplest way to execute code in another application domain. O exemplo define uma classe chamada Worker que herda MarshalByRefObject, com um método que exibe o nome do domínio do aplicativo no qual ele está em execução.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. O exemplo cria instâncias de Worker no domínio de aplicativo padrão e em um novo domínio de aplicativo.The example creates instances of Worker in the default application domain and in a new application domain.

Observação

O assembly que contém Worker deve ser carregado em ambos os domínios de aplicativo, mas ele pode carregar outros assemblies que existiriam apenas no novo domínio do aplicativo.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 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"
 */
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"

Exemplo 2Example 2

O exemplo a seguir demonstra uma classe derivada de MarshalByRefObject comunicação remota que é usada posteriormente.The following example demonstrates a class derived from MarshalByRefObject that is used later in remoting.

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 ) );
   }

};
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

Comentários

Um domínio de aplicativo é uma partição em um processo de sistema operacional em que um ou mais aplicativos residem.An application domain is a partition in an operating system process where one or more applications reside. Objetos no mesmo domínio do aplicativo se comunicar diretamente.Objects in the same application domain communicate directly. Objetos em diferentes domínios de aplicativo se comunicar por transporte cópias dos objetos entre limites de domínio de aplicativo ou por meio de um proxy para trocar mensagens.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 é a classe base para objetos que se comunicam entre os limites de domínio de aplicativo por meio da troca mensagens usando um proxy.MarshalByRefObject is the base class for objects that communicate across application domain boundaries by exchanging messages using a proxy. Objetos que não herdam MarshalByRefObject são implicitamente marshaling por valor.Objects that do not inherit from MarshalByRefObject are implicitly marshal by value. Quando um aplicativo remoto faz referência a um pacote por objeto de valor, uma cópia do objeto é passada entre limites de domínio de aplicativo.When a remote application references a marshal by value object, a copy of the object is passed across application domain boundaries.

MarshalByRefObject objetos são acessados diretamente dentro dos limites do domínio do aplicativo local.MarshalByRefObject objects are accessed directly within the boundaries of the local application domain. Domínio de aplicativo de na primeira vez que um aplicativo em um controle remoto acessa um MarshalByRefObject, um proxy é passado para o aplicativo remoto.The first time an application in a remote application domain accesses a MarshalByRefObject, a proxy is passed to the remote application. As chamadas subsequentes no proxy são empacotadas novamente para o objeto que residem no domínio do aplicativo local.Subsequent calls on the proxy are marshaled back to the object residing in the local application domain.

Tipos devem herdar da MarshalByRefObject quando o tipo é usado entre os limites de domínio de aplicativo e o estado do objeto não deve ser copiado porque os membros do objeto não são utilizáveis fora do domínio de aplicativo no qual eles foram criados.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.

Quando você deriva um objeto de MarshalByRefObject para uso nos limites do domínio de aplicativo, você não deve substituir qualquer um dos seus membros, nem deve chamar seus métodos diretamente.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. O tempo de execução reconhece que as classes derivadas de MarshalByRefObject devem passar por marshaling entre limites de domínio de aplicativo.The runtime recognizes that classes derived from MarshalByRefObject should be marshaled across app domain boundaries.

Construtores

MarshalByRefObject() MarshalByRefObject() MarshalByRefObject() MarshalByRefObject()

Inicializa uma nova instância da classe MarshalByRefObject.Initializes a new instance of the MarshalByRefObject class.

Métodos

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

GetType() GetType() GetType() GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object.

ToString() ToString() ToString() ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Inherited from Object)

Aplica-se a