ClientSponsor Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Предоставляет реализацию по умолчанию для класса спонсора по времени существования.
public ref class ClientSponsor : MarshalByRefObject, System::Runtime::Remoting::Lifetime::ISponsor
public class ClientSponsor : MarshalByRefObject, System.Runtime.Remoting.Lifetime.ISponsor
[System.Runtime.InteropServices.ComVisible(true)]
public class ClientSponsor : MarshalByRefObject, System.Runtime.Remoting.Lifetime.ISponsor
[System.Runtime.InteropServices.ComVisible(true)]
[System.Security.SecurityCritical]
public class ClientSponsor : MarshalByRefObject, System.Runtime.Remoting.Lifetime.ISponsor
type ClientSponsor = class
inherit MarshalByRefObject
interface ISponsor
[<System.Runtime.InteropServices.ComVisible(true)>]
type ClientSponsor = class
inherit MarshalByRefObject
interface ISponsor
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Security.SecurityCritical>]
type ClientSponsor = class
inherit MarshalByRefObject
interface ISponsor
Public Class ClientSponsor
Inherits MarshalByRefObject
Implements ISponsor
- Наследование
- Атрибуты
- Реализации
Примеры
В следующем примере показан класс ClientSponsor для расширения жизни активированного класса удаленного объекта.
#using <system.dll>
#using <system.runtime.remoting.dll>
#using <ClientSponsor_Share.dll>
using namespace System;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Channels;
using namespace System::Runtime::Remoting::Channels::Tcp;
using namespace System::Runtime::Remoting::Lifetime;
int main()
{
// Register a channel.
TcpChannel^ myChannel = gcnew TcpChannel;
ChannelServices::RegisterChannel( myChannel );
RemotingConfiguration::RegisterActivatedClientType(
RemotingSamples::HelloService::typeid, "tcp://localhost:8085/" );
// Get the remote Object*.
RemotingSamples::HelloService ^ myService = gcnew RemotingSamples::HelloService;
// Get a sponsor for renewal of time.
ClientSponsor^ mySponsor = gcnew ClientSponsor;
// Register the service with sponsor.
mySponsor->Register( myService );
// Set renewaltime.
mySponsor->RenewalTime = TimeSpan::FromMinutes( 2 );
// Renew the lease.
ILease^ myLease = dynamic_cast<ILease^>(mySponsor->InitializeLifetimeService());
TimeSpan myTime = mySponsor->Renewal( myLease );
Console::WriteLine( "Renewed time in minutes is {0}", myTime.Minutes );
// Call the remote method.
Console::WriteLine( myService->HelloMethod( "World" ) );
// Unregister the channel.
mySponsor->Unregister( myService );
mySponsor->Close();
}
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Lifetime;
namespace RemotingSamples
{
class HelloClient
{
static void Main()
{
// Register a channel.
TcpChannel myChannel = new TcpChannel ();
ChannelServices.RegisterChannel(myChannel);
RemotingConfiguration.RegisterActivatedClientType(
typeof(HelloService),"tcp://localhost:8085/");
// Get the remote object.
HelloService myService = new HelloService();
// Get a sponsor for renewal of time.
ClientSponsor mySponsor = new ClientSponsor();
// Register the service with sponsor.
mySponsor.Register(myService);
// Set renewaltime.
mySponsor.RenewalTime = TimeSpan.FromMinutes(2);
// Renew the lease.
ILease myLease = (ILease)mySponsor.InitializeLifetimeService();
TimeSpan myTime = mySponsor.Renewal(myLease);
Console.WriteLine("Renewed time in minutes is " + myTime.Minutes.ToString());
// Call the remote method.
Console.WriteLine(myService.HelloMethod("World"));
// Unregister the channel.
mySponsor.Unregister(myService);
mySponsor.Close();
}
}
}
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Tcp
Imports System.Runtime.Remoting.Lifetime
Namespace RemotingSamples
Class HelloClient
Shared Sub Main()
' Register a channel.
Dim myChannel As New TcpChannel()
ChannelServices.RegisterChannel(myChannel)
RemotingConfiguration.RegisterActivatedClientType( _
GetType(HelloService), "tcp://localhost:8085")
' Get the remote object.
Dim myService As New HelloService()
' Get a sponsor for renewal of time.
Dim mySponsor As New ClientSponsor()
' Register the service with sponsor.
mySponsor.Register(myService)
' Set renewaltime.
mySponsor.RenewalTime = TimeSpan.FromMinutes(2)
' Renew the lease.
Dim myLease As ILease = CType(mySponsor.InitializeLifetimeService(), ILease)
Dim myTime As TimeSpan = mySponsor.Renewal(myLease)
Console.WriteLine("Renewed time in minutes is " & myTime.Minutes)
' Call the remote method.
Console.WriteLine(myService.HelloMethod("World"))
' Unregister the channel.
mySponsor.Unregister(myService)
mySponsor.Close()
End Sub
End Class
End Namespace 'RemotingSamples
Комментарии
Текущая реализация спонсора времени существования может использоваться для спонсирования объектов, указав требуемое продление TimeSpan.
Замечание
Этот класс делает спрос на связь и спрос на наследование на уровне класса. Возникает SecurityException , если непосредственный вызывающий или производный класс не имеют разрешения инфраструктуры.
Конструкторы
| Имя | Описание |
|---|---|
| ClientSponsor() |
Инициализирует новый экземпляр ClientSponsor класса со значениями по умолчанию. |
| ClientSponsor(TimeSpan) |
Инициализирует новый экземпляр ClientSponsor класса с временем продления спонсируемого объекта. |
Свойства
| Имя | Описание |
|---|---|
| RenewalTime |
Возвращает или задает время TimeSpan существования спонсируемых объектов при запросе продления. |
Методы
| Имя | Описание |
|---|---|
| Close() |
Очищает объекты списка, зарегистрированные в текущем ClientSponsor. |
| CreateObjRef(Type) |
Создает объект, содержащий все соответствующие сведения, необходимые для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. (Унаследовано от MarshalByRefObject) |
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| Finalize() |
Освобождает ресурсы текущего ClientSponsor , прежде чем сборщик мусора освобождает их. |
| GetHashCode() |
Служит в качестве хэш-функции по умолчанию. (Унаследовано от Object) |
| GetLifetimeService() |
Устаревшие..
Извлекает текущий объект службы времени существования, который управляет политикой времени существования для этого экземпляра. (Унаследовано от MarshalByRefObject) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| InitializeLifetimeService() |
Инициализирует новый экземпляр ClientSponsor, предоставляющий аренду для текущего объекта. |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| MemberwiseClone(Boolean) |
Создает неглубокую копию текущего MarshalByRefObject объекта. (Унаследовано от MarshalByRefObject) |
| Register(MarshalByRefObject) |
Регистрирует указанный MarshalByRefObject для спонсорства. |
| Renewal(ILease) |
Запрашивает у спонсора клиента продление аренды указанного объекта. |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
| Unregister(MarshalByRefObject) |
Отменяет регистрацию указанного MarshalByRefObject из списка объектов, спонсируемых текущим ClientSponsor. |