title: In-process communication design with WCF (.NET)
body: <p>I have an interesting design problem and I was hoping you all could make some suggestions.  I'm using C# and .NET 3.0</p>
  
  <p>I have a very nice, extensible framework built on top of WCF that automates the setup of endpoints and the creation of contracts.  The system I'm working in could be run in different ways - endpoints could be somewhere else on the internet, running in different assemblies on the same box, or even running in the same process.  WCF is great for making all of this transparent, but in the last case, I'd like to improve efficiency:</p>
  
  <p>I'd love to avoid the overhead of serializing objects that aren't really going anywhere.  There's really no point in doing that to communicate between two threads in the same assembly.  At the same time, I'd like to utilize the WCF-based framework that's already in place, because it will be a lot easier to maintain if we don't have two separate communications pathways depending on the setup of the system.</p>
  
  <p>My first thought was to use object pointers in an unsafe context - to not fight the serialization, but to only serialize the minimum amount.  My concern with this is that on asynchronous messages in environments where the GC is being aggressive, the message might and probably will be gone before we have a chance to dereference the pointer contained in it, which would lead to plenty of issues.</p>
  
  <p>My next thought was to use GCHandles, but I'm unsure about their behavior - if a GCHandle isn't referenced anymore, but contains a reference to a managed object, are both cleaned up by the GC, or neither?  I'm worried about introducing a huge memory leak by using these, because the chance that a message will get lost is great, and we won't be able to call Free(), and the documentation I can find is... lacking.</p>
  
  <p>Another thought is to use reflection to look at all managed objects, but it seems like the overhead for this would be huge, and this system must be as efficient as possible.</p>
  
  <p>So, in summary, I'm trying to send an object across a process with WCF without serializing it, which as far as I can tell means keeping it alive even if it temporarily has no references.  It seems like it should be possible, but I wonder if I'm trying to have my cake and eat it too.</p>
  
  <p>Thank you so much for your input!</p>