runtime: Memory is not released when using TransactionScope with async option
Sample code
while (true)
{
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
scope.Complete();
}
}
Memory usage grows, and response times increase until the web api halts. Removing the async option resolves the issue, but async is required in my case. đ
Workaround (not perfect, see comment)
I created a factory (singleton) around it to manually trigger GC, something like this simplified:
public class TransactionScopeFactory
{
private const int GcThreshold = 200_000;
private static int _createdScopes = 0;
public TransactionScope CreateScope()
{
int currentCreatedScopes = Interlocked.Increment(ref _createdScopes);
if (currentCreatedScopes >= GcThreshold)
{
if (Interlocked.CompareExchange(ref _createdScopes, 0, GcThreshold) >= GcThreshold)
{
GC.Collect(2);
}
}
return new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
}
}
Questions
- Is the workaround okay? Iâm a bit hesitant about manual GC, as the docs advises against it without a clear purpose and the TransactionScope docs doesnât mention anything about manually invoking GC.
- Why does the workaround only work in release mode? It doesnât seem to work in debug mode.
Used versions: .NET 8, 9
Thank you đ
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Reactions: 2
- Comments: 19 (10 by maintainers)
Please see #50683 for more information about this. To answer a few things brought up in this issue:
ConditionalWeakTableinternally used by it) creates a finalizable object graph that is problematic for garbage collection - basically all of the objects require gen2 in order to make progress even though they seem like they should be short-lived. When the program approaches the memory limit, the frequent gen2s limit further growth. However, the app shouldnât be using anywhere near that much memory, so while itâs not the traditional kind of âleakâ itâs still a problem.The
>=makes sure that you still gettrueas a result since the return value from the compare-exchange might be larger, but it doesnât impact the operation of the compare-exchange itself, which is âupdate if the old value equals GcThresholdâ, not âupdate if the old value is greater than GcThresholdâ. Just use a lock around the increment and compare-exchange (and then they donât need to be interlocked) as a simpler solution.