Skip to content

Commit

Permalink
Improve memory situation by avoiding linked cancellation tokens compl…
Browse files Browse the repository at this point in the history
…etely.

- Use a custom registration when checking for host dispose.
  • Loading branch information
davidfowl committed Oct 31, 2012
1 parent a2d13e8 commit 264fd0b
Showing 1 changed file with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,15 @@ public abstract class TransportDisconnectBase : ITrackingConnection
private readonly IPerformanceCounterManager _counters;
private string _connectionId;
private int _ended;

// Token that represents the end of the connection based on a combination of
// conditions (timeout, disconnect, connection forcibly ended, host shutdown)
private CancellationToken _connectionEndToken;
private CancellationTokenSource _connectionEndTokenSource;

// Token that represents the host shutting down
private CancellationToken _hostShutdownToken;
private CancellationTokenRegistration _hostRegistration;

// Queue to protect against overlapping writes to the underlying response stream
private readonly TaskQueue _writeQueue = new TaskQueue();
Expand Down Expand Up @@ -207,6 +208,8 @@ public void End()
{
_connectionEndTokenSource.Dispose();
}

_hostRegistration.Dispose();
}
}

Expand All @@ -230,8 +233,24 @@ protected void InitializePersistentState()
Completed = new TaskCompletionSource<object>();

// Create a token that represents the end of this connection's life
_connectionEndTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_hostShutdownToken);
_connectionEndTokenSource = new CancellationTokenSource();
_connectionEndToken = _connectionEndTokenSource.Token;

// Handle the shutdown token's callback so we can end our token if it trips
_hostRegistration = _hostShutdownToken.Register(state =>
{
try
{
((CancellationTokenSource)state).Cancel();
}
catch(ObjectDisposedException)
{
// We've already disposed the token and we don't need to do any clean up
// or triggering so just swallow the exception
}
},
_connectionEndTokenSource,
useSynchronizationContext: false);
}

protected ITransportConnection Connection { get; set; }
Expand Down

0 comments on commit 264fd0b

Please sign in to comment.