Singleton Objects

Singleton objects resemble client-activated objects in that they retain state; but the server, not the client, creates them. Only one instance of a singleton object is ever created, and it can serve any number of concurrent clients. Because the .NET Remoting services are multithreaded, clients can call methods on this object simultaneously. However, you must ensure that the object itself is thread-safe. If you modify a member variable in a singleton method, for example, you must ensure that you obtain an exclusive lock first. Otherwise, updates might be lost or inconsistent data might be applied.

We can alter the preceding example to use a singleton object without worrying. The single GetActiveDomain method just returns a static piece of information to the calling client, and this method can therefore be called concurrently without causing any problems.

The server configuration file looks the same as the SingleCall example, except for the different mode attribute, as shown in Listing 4-16.

Listing 4-16 A component host that uses a singleton object
 <configuration>    <system.runtime.remoting>       <application name="SimpleServer">          <service>             <wellknown mode="Singleton"                        type="RemoteObjects.RemoteObject, RemoteObjects"                        objectUri="RemoteObject" />          </service>          <channels>             <channel ref="tcp server" port="8080" />          </channels>       </application>    </system.runtime.remoting> </configuration> 

The client configuration file looks exactly the same for the singleton object as for a SingleCall object.

Singleton objects are somewhat difficult to work with and can't be load-balanced over multiple computers. In some scenarios, however, such as those that involve synchronizing and communicating among multiple clients, a singleton object provides the most elegant solution. Chapter 7 takes a closer look at singleton objects and the threading techniques you need to use them safely.



Microsoft. NET Distributed Applications(c) Integrating XML Web Services and. NET Remoting
MicrosoftВ® .NET Distributed Applications: Integrating XML Web Services and .NET Remoting (Pro-Developer)
ISBN: 0735619336
EAN: 2147483647
Year: 2005
Pages: 174

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net