Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is caching WCF channels a bad thing?

I've been reading a lot of WCF articles online and it seems like most people cache the ChannelFactory objects but not the channels itself. It appears that most people are afraid to use channel caching because they don't want to handle the network faults that could render the cached channel unusable. But that could be easily fixed by catching the CommunicationException on the method, recreate the channel, and replay the method using Reflection.

Then there are people who think it's bad to do channel caching because all communication will go through a single channel. See following article.

http://social.msdn.microsoft.com/Forums/is/wcf/thread/9cbdf92a-a749-40ce-9ebe-3f2622cd78ee

Is this necessarily a bad thing? Can you not share channels across threads? Will performance suffer because multiple method calls made to this single channel will get processed serially?

I haven't found evidence that sharing channels will degrade performance. What I did find is that using a cached channel is about 5 times faster than using a non-cached channel, even if it means having to use Reflection to make the methods calls on the cached channels.

The other advantage is not having to surround all your WCF calls with try/catch/finally statements to call Close(), Abort(), or Dispose() on the channel when you are done with it. To me it seems like WCF took a step in the wrong direction by forcing developers to have to manage WCF channel resources. In .NET Remoting, you created the proxy using the Activator class and you didn't have to do anything to it to clean it up. The .NET Framework handled all of that for you.

like image 368
Bart Avatar asked May 31 '11 21:05

Bart


1 Answers

2 main reasons:

  1. A ChannelFactory is expensive to create and it is thread safe => perfect candidate for caching.
  2. A Channel generated by a channel factory is not expensive to create but it is not thread safe (well in reality it is thread safe but concurrent calls will be blocked and executed sequentially) => don't cache it in a multithreaded environment.

Here's a nice article which goes into further details.

like image 51
Darin Dimitrov Avatar answered Sep 21 '22 08:09

Darin Dimitrov