private Task ProcessMessages(ITransportConnection connection, Func<Task> initialize)
{
var disposer = new Disposer();
if (BeforeCancellationTokenCallbackRegistered != null)
{
BeforeCancellationTokenCallbackRegistered();
}
var cancelContext = new ForeverTransportContext(this, disposer);
// Ensure delegate continues to use the C# Compiler static delegate caching optimization.
_busRegistration = ConnectionEndToken.SafeRegister(state => Cancel(state), cancelContext);
if (BeforeReceive != null)
{
BeforeReceive();
}
try
{
// Ensure we enqueue the response initialization before any messages are received
EnqueueOperation(state => InitializeResponse((ITransportConnection)state), connection)
.Catch((ex, state) => ((ForeverTransport)state).OnError(ex), this, Logger);
// Ensure delegate continues to use the C# Compiler static delegate caching optimization.
IDisposable subscription = connection.Receive(LastMessageId,
(response, state) => ((ForeverTransport)state).OnMessageReceived(response),
MaxMessages,
this);
if (AfterReceive != null)
{
AfterReceive();
}
// Ensure delegate continues to use the C# Compiler static delegate caching optimization.
initialize().Catch((ex, state) => ((ForeverTransport)state).OnError(ex), this, Logger)
.Finally(state => ((SubscriptionDisposerContext)state).Set(),
new SubscriptionDisposerContext(disposer, subscription));
}
catch (Exception ex)
{
_transportLifetime.Complete(ex);
}
return _requestLifeTime.Task;
}