-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Re-use cancellation tokens in the https middleware #31528
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using System.Collections.Concurrent; | ||
using System.Threading; | ||
|
||
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal | ||
{ | ||
internal class CancellationTokenSourcePool | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't this be disposable and dispose all tokens in the queue? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I put a note about it in the PR description.
|
||
{ | ||
private const int MaxQueueSize = 1024; | ||
|
||
private readonly ConcurrentQueue<PooledCancellationTokenSource> _queue = new(); | ||
private int _count; | ||
|
||
public PooledCancellationTokenSource Rent() | ||
{ | ||
if (_queue.TryDequeue(out var cts)) | ||
{ | ||
Interlocked.Decrement(ref _count); | ||
return cts; | ||
} | ||
return new PooledCancellationTokenSource(this); | ||
} | ||
|
||
private bool Return(PooledCancellationTokenSource cts) | ||
{ | ||
if (Interlocked.Increment(ref _count) > MaxQueueSize || !cts.TryReset()) | ||
{ | ||
Interlocked.Decrement(ref _count); | ||
return false; | ||
} | ||
|
||
_queue.Enqueue(cts); | ||
return true; | ||
} | ||
|
||
/// <summary> | ||
/// A <see cref="CancellationTokenSource"/> with a back pointer to the pool it came from. | ||
/// Dispose will return it to the pool. | ||
/// </summary> | ||
public class PooledCancellationTokenSource : CancellationTokenSource | ||
{ | ||
private readonly CancellationTokenSourcePool _pool; | ||
|
||
public PooledCancellationTokenSource(CancellationTokenSourcePool pool) | ||
{ | ||
_pool = pool; | ||
} | ||
|
||
protected override void Dispose(bool disposing) | ||
{ | ||
if (disposing) | ||
{ | ||
// If we failed to return to the pool then dispose | ||
if (!_pool.Return(this)) | ||
{ | ||
base.Dispose(disposing); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} |
Uh oh!
There was an error while loading. Please reload this page.