Resources and Services
Synchronizing access to the service instance using
ConcurrencyMode.Single
or an explicit
synchronization lock only manages concurrent access to the service
instance state itself. It does not provide safe access to the underlying
resources the service may be using. These resources must also be
thread-safe. For example, consider the application shown in Figure 8-2.
Figure 8-2. Applications must synchronize access to resources
Even though the service instances are thread-safe, the two instances try to concurrently access the same resource (such as a static variable, a helper static class, or a file), and therefore the resource itself must have synchronized access. This is true regardless of the service instancing mode. Even a per-call service could run into the situation shown in Figure 8-2.
Deadlocked Access
The naive solution to providing thread-safe access to resources is to provide each resource with its own lock, potentially encapsulating that lock in the resource itself, and ask the resource to lock the lock when it’s accessed and unlock the lock when the service is done with the resource. The problem with this approach is that it is deadlock-prone. Consider the situation depicted in Figure 8-3.
Figure 8-3. Deadlock over resources access
In the figure, Instance A ...
Get Programming WCF Services, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.