If you have implementation code ready for server in
SAO-SingleCall we need a very small change to change it to SAO-Singleton
activation. For example, in Code Listing 1 which is implemented for
SAO-SingleCall, we can just modify WellKnownObjectMode.SingleCall to
WellKnownObjectMode.Singleton in the Module1.vb. So our complete Module1.vb
code could be as given below.
Listing 3: Module1.vb for SAO-Singleton activation
Imports System
Imports System.IO
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Http
Module Module1
Sub Main()
' ------- SAO Singleton ----------
Dim channel As HttpChannel = New HttpChannel(1)
Try
ChannelServices.RegisterChannel(channel, False)
Dim serverType As Type = Type.GetType("RemoteServer.CServer")
RemotingConfiguration.RegisterWellKnownServiceType(serverType, _
"TestRemoteServer", WellKnownObjectMode.Singleton)
Console.WriteLine("Remote Service started...Press Enter key to stop." _
& Now.ToString())
Console.Read()
Catch ex As Exception
Console.WriteLine(ex.ToString())
Console.Read()
ChannelServices.UnregisterChannel(channel)
Finally
End Try
' ---------------------------------
End Sub
End Module
At minimum we can leave Server.vb (Listing 2) unchanged for
the test.
Idea behind Singleton activation
In the case of SAO, Singleton activation, the server creates
single and shared remote instance for all clients. So the remote object's
constructor New() will run only once at the server. For example, if client A
halts at the server at some point of time, then a remote call from other clients
(say B,C,D, etc.) will remain in the queue and wait until client A finishes the
execution at the server. When a call from client A completes its execution at
server then other client's calls will be processed by picking it from the
waiting queue.
In the example given above, let us consider a situation. At
certain point of execution if client A uses Thread.Sleep(20000) to
sleep for 20 seconds, other client's remote method calls continues normally by
picking one-by-one from the queue. Client A will resume its execution
after 20 seconds.
Therefore, in Singleton activation we can do state
management and do variables/values sharing among clients. For example, we can
implement to count total number of client calls using shared member variable at
server and incrementing it by 1 in the remote method.
All the above scenarios are possible because the server
creates only one instance of an object for all clients in SAO - Singleton
activation.