开发者

WCF: Instancing and Concurrency question

开发者 https://www.devze.com 2023-01-24 16:23 出处:网络
Say I have a WCF service that has access to some data that is shared between multiple clien开发者_如何学运维ts. What is the difference between these two setups:

Say I have a WCF service that has access to some data that is shared between multiple clien开发者_如何学运维ts. What is the difference between these two setups:

1) Instancing: Single, Concurrency: Multiple, with the shared data stored in instance variables.

2) Instancing: Per-Call, Concurrency: Multiple, with the shared data stored in static variables.

Is there any practical difference? Either way, I will have to make sure the shared data is thread-safe, but I'm wondering if there are any advantages for one particular approach.


Notionally, there is no difference. As you've said, either way you're gonna have to synchronize access to the shared data. Practically, the second option is better. From the definitive book on WCF, Programming WCF Services by Juval Lowy:

...per-call services are actually the preferred instance management mode for WCF services...recommend that you avoid singletons in the general case and find ways to share the state of the singleton instead of the singleton instance itself.

I use option #2 for my project. The WCF service itself is simply a thin facade to static methods of the classes where the work is performed. For example,

public class Logger
{
    private static List<Logger> _loggers = new List<Logger>();
    private static object _sync = new object();

    public static void Start()
    {
        Logger logger = new Logger();
        logger.Start();

        lock (_sync) {
            _loggers.Add( logger );
        }
    }

    private Logger()
    {
        // construct the Logger object...
    }

    private void Start()
    {
        // start the logger here...
    }
}

public class LoggingService : ILoggingService
{
    public void StartLogger()
    {
        Logger.Start();
    }
}

Obviously, I've elided many of the details, but this shows the general idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消