private NanomsgReadStream ReceiveStream(SendRecvFlags flags) { IntPtr buffer = IntPtr.Zero; int rc = Interop.nn_recv(_socket, ref buffer, Constants.NN_MSG, (int)flags); if (rc < 0 || buffer == null) { return(null); } /* * In order to prevent managed allocations per receive, we attempt to recycle stream objects. This * will work optimally if the stream is disposed before the next receive call, as in this case each * socket class will always reuse the same stream. * * Disposing the stream will both release its nanomsg-allocated native buffer and return it to its * socket class for reuse. */ var stream = Interlocked.Exchange(ref _recycledReadStream, null); if (stream != null) { stream.Reinitialize(buffer, rc); } else { stream = new NanomsgReadStream(buffer, rc, _freeReadDisposer ?? (_freeReadDisposer = new NanomsgNativeDisposer() { Socket = (NanomsgSocketBase)this })); } return(stream); }
private void RecycleStream(NanomsgReadStream messageStream) { _recycledReadStream = messageStream; }