The MSMQ and SQL Server transports cache exceptions in memory to allow transactions to be cleared before executing recoverability policies. Therefore, exceptions with large memory footprints can cause excessive memory consumption. Furthermore, the cache may retain items for longer when the endpoint is scaled out. This page describes how to solve issues caused by excessive memory consumption due to this caching.
Dispose of exception specific resources
An exception may be caught to explicitly dispose of resources before it is rethrown and cached.
For example, disposing the response body contained in a WebException
may significantly reduce the amount of memory required to cache the exception:
class DisposeLargeExceptionsBehavior : Behavior<IIncomingPhysicalMessageContext>
{
public override async Task Invoke(IIncomingPhysicalMessageContext context, Func<Task> next)
{
try
{
await next();
}
catch (WebException webException)
{
// dispose expensive resources:
webException.Response?.Dispose();
// rethrow to let recoverability handle the exception:
throw;
}
}
}
See pipeline customization documentation for more details.