AsyncLocal<T>与ThreadLocal<T>区别研究
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ATLearn { /// <summary> /// Guid工厂 /// </summary> static class GuidFactory { private static ThreadLocal<string> _localGuid = new ThreadLocal<string>(); //private static AsyncLocal<string> _localGuid = new AsyncLocal<string>(); public static string CurrentGuid { get { if (_localGuid.Value == null) { _localGuid.Value = Guid.NewGuid().ToString(); } return _localGuid.Value; } } } class APP { private Task<int> awaitFunction() { return Task.Run<int>(() => { Console.WriteLine("awaitFunction:" + GuidFactory.CurrentGuid); return 0; }); } private async void asyncFunction() { Console.WriteLine("asyncFunction:" + GuidFactory.CurrentGuid); int num = await awaitFunction(); Console.WriteLine("asyncFunction:" + GuidFactory.CurrentGuid); } public APP() { asyncFunction(); asyncFunction(); while (true) { Thread.Sleep(1000); } } } class Program { static void Main(string[] args) { APP App = new APP(); } } }
/// <summary> /// Guid工厂 /// </summary> static class GuidFactory { //private static ThreadLocal<string> _localGuid = new ThreadLocal<string>(); private static AsyncLocal<string> _localGuid = new AsyncLocal<string>(); public static string CurrentGuid { get { if (_localGuid.Value == null) { _localGuid.Value = Guid.NewGuid().ToString(); } return _localGuid.Value; } } }