[c#] The principle and detailed usage examples of ThreadLocal

illustrate

ThreadLocal is a thread-local storage class in C# that provides an easy way to store thread-specific data. Each ThreadLocal instance maintains a list of copies of values ​​of type T, where each thread has its own independent copy. In this way, the data can be independently accessed and modified by different threads without affecting each other.

Specifically, when using ThreadLocal, each thread gets a copy of the T type, which can be accessed and modified through the Value property. If a thread modifies its copy, no other threads are affected. ThreadLocal can help you avoid race conditions and conflicts between threads when dealing with multithreaded applications.

sample code

using System.Collections.Generic;
using System.Threading;

namespace xxxx.ThreadLocal
{
    
    
    /// <summary>
    /// ThreadLocal 使用
    /// </summary>
    public class ThreadLocalDic
    {
    
    
        /// <summary>
        /// 保存 线程变量副本
        /// </summary>
        private static ThreadLocal<Dictionary<string, string>> NAMESPACE = new ThreadLocal<Dictionary<string, string>>(() => new Dictionary<string, string>());

        /// <summary>
        /// 保存 数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void Set(string key, string value)
        {
    
    
            var keyValues = NAMESPACE?.Value;
            if (keyValues == null)
            {
    
    
                return;
            }
            if (keyValues.ContainsKey(key))
            {
    
    
                return;
            }
            keyValues?.Add(key, value);
        }

        /// <summary>
        /// 获取值
        /// </summary>
        /// <returns>线程副本</returns>
        public static Dictionary<string, string> Get()
        {
    
    
            return NAMESPACE?.Value;
        }

        /// <summary>
        /// 移除信息
        /// </summary>
        public static void Remove()
        {
    
    
            NAMESPACE?.Value?.Clear();
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_38428623/article/details/131086777