Skip to content

Eliminate unnecessary AsyncLocal allocation if SessionId isn't changed #1453

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

Merged
merged 2 commits into from
Nov 26, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 38 additions & 12 deletions src/NHibernate/Impl/SessionIdLoggingContext.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
using System;
#if !NETSTANDARD2_0 && !NETCOREAPP2_0
using System.Runtime.Remoting.Messaging;
#else
using System.Threading;
#endif

namespace NHibernate.Impl
{
public class SessionIdLoggingContext : IDisposable
{
private static readonly AsyncLocal<Guid?> _currentSessionId = new AsyncLocal<Guid?>();

#if NETSTANDARD2_0 || NETCOREAPP2_0
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.net standard and .net core do not support CallContext

private static readonly Lazy<AsyncLocal<Guid?>> _currentSessionId =
new Lazy<AsyncLocal<Guid?>>(() => new AsyncLocal<Guid?>(), true);
#else
private const string LogicalCallContextVariableName = "__" + nameof(SessionIdLoggingContext) + "__";
#endif
private readonly Guid? _oldSessonId;

private readonly bool _hasChanged;

public SessionIdLoggingContext(Guid id)
{
_oldSessonId = SessionId;
SessionId = id;
_hasChanged = _oldSessonId != id;
if (_hasChanged)
{
SessionId = id;
}
}

/// <summary>
Expand All @@ -24,17 +37,30 @@ public SessionIdLoggingContext(Guid id)
/// </summary>
public static Guid? SessionId
{
get => _currentSessionId.Value;
set => _currentSessionId.Value = value;
get
{
#if NETSTANDARD2_0 || NETCOREAPP2_0
return _currentSessionId.IsValueCreated ? _currentSessionId.Value.Value : null;
#else
return (Guid?) CallContext.LogicalGetData(LogicalCallContextVariableName);
#endif
}
set
{
#if NETSTANDARD2_0 || NETCOREAPP2_0
_currentSessionId.Value.Value = value;
#else
CallContext.LogicalSetData(LogicalCallContextVariableName, value);
#endif
}
}

#region IDisposable Members

public void Dispose()
{
SessionId = _oldSessonId;
if (_hasChanged)
{
SessionId = _oldSessonId;
}
}

#endregion
}
}
}