.NET Core equivalent of CallContext.LogicalGet/SetData

陌路散爱 提交于 2019-12-05 00:24:24

Had this problem when we switched a library from .Net Framework to .Net Standard and had to replace System.Runtime.Remoting.Messaging CallContext.LogicalGetData and CallContext.LogicalSetData.

I followed this guide to replace the methods:

http://www.cazzulino.com/callcontext-netstandard-netcore.html

/// <summary>
/// Provides a way to set contextual data that flows with the call and 
/// async context of a test or invocation.
/// </summary>
public static class CallContext
{
    static ConcurrentDictionary<string, AsyncLocal<object>> state = new ConcurrentDictionary<string, AsyncLocal<object>>();

    /// <summary>
    /// Stores a given object and associates it with the specified name.
    /// </summary>
    /// <param name="name">The name with which to associate the new item in the call context.</param>
    /// <param name="data">The object to store in the call context.</param>
    public static void SetData(string name, object data) =>
        state.GetOrAdd(name, _ => new AsyncLocal<object>()).Value = data;

    /// <summary>
    /// Retrieves an object with the specified name from the <see cref="CallContext"/>.
    /// </summary>
    /// <param name="name">The name of the item in the call context.</param>
    /// <returns>The object in the call context associated with the specified name, or <see langword="null"/> if not found.</returns>
    public static object GetData(string name) =>
        state.TryGetValue(name, out AsyncLocal<object> data) ? data.Value : null;
}

You can use a dictionary of AsyncLocal to simulate exactly the API and behavior of the original CallContext. See http://www.cazzulino.com/callcontext-netstandard-netcore.html for a complete implementation example.

I guess you could use ThreadStatic since what I heard CallContext is/was "just" an abstraction over ThreadStatic with automatic transfer of state between threads in the call stack.

Also, you could/should use AsyncLocal/ThreadLocal instead. AsyncLocal seem to be pretty much what CallContext was.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!