net ThreadStatic 线程级别的缓存

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Hello World!");
            var task1 = Task.Run(() =>
            {
                if (Test.cachedDict == null)
                {
                    Test.cachedDict = new Dictionary<int, string>();
                }
                Test.cachedDict.Add(1, "mar");
                Test.cachedDict.Add(2, "joker");
                Test.cachedDict.Add(6, "sss");
                Test.cachedDict.Add(7, "st");
                Console.WriteLine($"no1 thread={Thread.CurrentThread.ManagedThreadId}的dict记录是{Test.cachedDict.Count}");
            
            });
            var task2 = Task.Run(() =>
            {
                if (Test.cachedDict == null)
                {
                    Test.cachedDict = new Dictionary<int, string>();
                }
                Test.cachedDict.Add(3, "python");
                Test.cachedDict.Add(4, "sql");
                Test.cachedDict.Add(5, "r");
                Console.WriteLine($"thread={Thread.CurrentThread.ManagedThreadId}的dict记录是{Test.cachedDict.Count}");
            });
            Console.Read();
        }
    }
    public class Test
    {
        [ThreadStatic]
        public static Dictionary<int, string> cachedDict = new Dictionary<int, string>();
    }
}

作者:spike

分类: Net

创作时间:2023-06-25

更新时间:2024-12-09

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1