Skip to content
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

[WIP] added ThreadLocalScopeManager #88

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
42 changes: 42 additions & 0 deletions src/OpenTracing/Util/ThreadLocalScope.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
namespace OpenTracing.Util
{
/// <inheritdoc />
/// <summary>
/// A <see cref="T:OpenTracing.IScope" /> primitive that relies on thread local storage for
/// managing active scopes. Intended to be used in systems where multiple logical,
/// related operations are all executed in the same thread albeit at different times.
/// </summary>
public class ThreadLocalScope : IScope
{
private readonly ThreadLocalScopeManager _scopeManager;
private readonly bool _finishOnDispose;
private readonly IScope _scopeToRestore;

public ThreadLocalScope(ThreadLocalScopeManager scopeManager, ISpan wrappedSpan, bool finishOnDispose)
{
_scopeManager = scopeManager;
Span = wrappedSpan;
_finishOnDispose = finishOnDispose;
_scopeToRestore = scopeManager.Active;
scopeManager.Active = this;
}

public void Dispose()
{
if (_scopeManager.Active != this)
{
// This shouldn't happen if users call methods in the expected order. Bail out.
return;
}

if (_finishOnDispose)
{
Span.Finish();
}

_scopeManager.Active = _scopeToRestore;
}

public ISpan Span { get; }
}
}
30 changes: 30 additions & 0 deletions src/OpenTracing/Util/ThreadLocalScopeManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;

namespace OpenTracing.Util
{
/// <summary>
/// An <see cref="IScopeManager"/> implementation that relies on thread local storage for
/// managing active scopes. Intended to be used in systems where multiple logical,
/// related operations are all executed in the same thread albeit at different times.
/// </summary>
public class ThreadLocalScopeManager : IScopeManager
{
/*
* Went with ThreadStatic over ThreadLocal<T> because we don't
* want scopes to be initialized upon thread initialization by default
* and we want ThreadStatic's mutability for restoring / replacing scopes.
*/
[ThreadStatic]
private static IScope _active;

public IScope Active
{
get => _active;
set => _active = value;
}
public IScope Activate(ISpan span, bool finishSpanOnDispose)
{
return new ThreadLocalScope(this, span, finishSpanOnDispose);
}
}
}