Skip to content

Commit 15c95da

Browse files
authored
Eliminate unnecessary AsyncLocal allocation if SessionId isn't changed (#1453)
- Use CallContext.LogicalGetData/LogicalSetData instead of AsyncLocal<T> on Full .NET Fx
1 parent 1b410b2 commit 15c95da

File tree

1 file changed

+38
-12
lines changed

1 file changed

+38
-12
lines changed
Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,31 @@
11
using System;
2+
#if !NETSTANDARD2_0 && !NETCOREAPP2_0
3+
using System.Runtime.Remoting.Messaging;
4+
#else
25
using System.Threading;
6+
#endif
37

48
namespace NHibernate.Impl
59
{
610
public class SessionIdLoggingContext : IDisposable
711
{
8-
private static readonly AsyncLocal<Guid?> _currentSessionId = new AsyncLocal<Guid?>();
9-
12+
#if NETSTANDARD2_0 || NETCOREAPP2_0
13+
private static readonly Lazy<AsyncLocal<Guid?>> _currentSessionId =
14+
new Lazy<AsyncLocal<Guid?>>(() => new AsyncLocal<Guid?>(), true);
15+
#else
16+
private const string LogicalCallContextVariableName = "__" + nameof(SessionIdLoggingContext) + "__";
17+
#endif
1018
private readonly Guid? _oldSessonId;
11-
19+
private readonly bool _hasChanged;
20+
1221
public SessionIdLoggingContext(Guid id)
1322
{
1423
_oldSessonId = SessionId;
15-
SessionId = id;
24+
_hasChanged = _oldSessonId != id;
25+
if (_hasChanged)
26+
{
27+
SessionId = id;
28+
}
1629
}
1730

1831
/// <summary>
@@ -24,17 +37,30 @@ public SessionIdLoggingContext(Guid id)
2437
/// </summary>
2538
public static Guid? SessionId
2639
{
27-
get => _currentSessionId.Value;
28-
set => _currentSessionId.Value = value;
40+
get
41+
{
42+
#if NETSTANDARD2_0 || NETCOREAPP2_0
43+
return _currentSessionId.IsValueCreated ? _currentSessionId.Value.Value : null;
44+
#else
45+
return (Guid?) CallContext.LogicalGetData(LogicalCallContextVariableName);
46+
#endif
47+
}
48+
set
49+
{
50+
#if NETSTANDARD2_0 || NETCOREAPP2_0
51+
_currentSessionId.Value.Value = value;
52+
#else
53+
CallContext.LogicalSetData(LogicalCallContextVariableName, value);
54+
#endif
55+
}
2956
}
3057

31-
#region IDisposable Members
32-
3358
public void Dispose()
3459
{
35-
SessionId = _oldSessonId;
60+
if (_hasChanged)
61+
{
62+
SessionId = _oldSessonId;
63+
}
3664
}
37-
38-
#endregion
3965
}
40-
}
66+
}

0 commit comments

Comments
 (0)