|
| 1 | +using System; |
| 2 | +using System.Diagnostics; |
| 3 | +using System.Threading; |
| 4 | +using System.Threading.Tasks; |
| 5 | + |
| 6 | +namespace ThreadingTest; |
| 7 | + |
| 8 | +public class AsyncLocalTest |
| 9 | +{ |
| 10 | + private readonly AsyncLocal<string> _asyncLocalString; |
| 11 | + private readonly AsyncLocal<Wrapper<string?>> _asyncLocalWrapper; |
| 12 | + |
| 13 | + public AsyncLocalTest() |
| 14 | + { |
| 15 | + _asyncLocalString = new AsyncLocal<string>(); |
| 16 | + _asyncLocalWrapper = new AsyncLocal<Wrapper<string?>> { Value = new Wrapper<string?>(null) }; |
| 17 | + } |
| 18 | + |
| 19 | + #region Methods |
| 20 | + |
| 21 | + public async Task AsyncLocal_TestAsync(CancellationToken cancellationToken = default) |
| 22 | + { |
| 23 | + // 设置 AsyncLocal 的值 |
| 24 | + _asyncLocalString.Value = "主线程的值"; |
| 25 | + Console.WriteLine($"主线程中 AsyncLocal 的值: {_asyncLocalString.Value}"); |
| 26 | + |
| 27 | + // 启动一个异步任务 |
| 28 | + await Task.Run( |
| 29 | + async () => |
| 30 | + { |
| 31 | + Console.WriteLine($"异步任务开始时 AsyncLocal 的值: {_asyncLocalString.Value}"); |
| 32 | + // 在异步任务中修改 AsyncLocal 的值 |
| 33 | + _asyncLocalString.Value = "异步任务的值"; |
| 34 | + Console.WriteLine($"异步任务中 AsyncLocal 的值: {_asyncLocalString.Value}"); |
| 35 | + |
| 36 | + // 启动另一个异步任务 |
| 37 | + await Task.Run( |
| 38 | + () => |
| 39 | + { |
| 40 | + Console.WriteLine($"嵌套异步任务中 AsyncLocal 的值: {_asyncLocalString.Value}"); |
| 41 | + }); |
| 42 | + }, |
| 43 | + cancellationToken); |
| 44 | + |
| 45 | + // 在主线程中再次访问 AsyncLocal 的值 |
| 46 | + Console.WriteLine($"主线程中 AsyncLocal 的值: {_asyncLocalString.Value}"); |
| 47 | + } |
| 48 | + |
| 49 | + public async Task Wrapper_TestAsync(CancellationToken cancellationToken = default) |
| 50 | + { |
| 51 | + Debug.Assert(_asyncLocalWrapper.Value != null, "AsyncLocal wrapper should not be null"); |
| 52 | + |
| 53 | + _asyncLocalWrapper.Value.Data = "主线程的值"; |
| 54 | + Console.WriteLine($"主线程中 AsyncLocal 的值: {_asyncLocalWrapper.Value.Data}"); |
| 55 | + |
| 56 | + await Task.Run( |
| 57 | + async () => |
| 58 | + { |
| 59 | + Console.WriteLine($"异步任务开始时 AsyncLocal 的值: {_asyncLocalWrapper.Value.Data}"); |
| 60 | + _asyncLocalWrapper.Value.Data = "异步任务的值"; |
| 61 | + Console.WriteLine($"异步任务中 AsyncLocal 的值: {_asyncLocalWrapper.Value.Data}"); |
| 62 | + |
| 63 | + await Task.Run( |
| 64 | + () => |
| 65 | + { |
| 66 | + Console.WriteLine($"嵌套异步任务中 AsyncLocal 的值: {_asyncLocalWrapper.Value.Data}"); |
| 67 | + }); |
| 68 | + }, |
| 69 | + cancellationToken); |
| 70 | + |
| 71 | + Console.WriteLine($"主线程中 AsyncLocal 的值: {_asyncLocalWrapper.Value.Data}"); |
| 72 | + } |
| 73 | + |
| 74 | + #endregion |
| 75 | + |
| 76 | + internal class Wrapper<T> |
| 77 | + { |
| 78 | + public Wrapper(T value) |
| 79 | + { |
| 80 | + Data = value; |
| 81 | + } |
| 82 | + |
| 83 | + #region Properties |
| 84 | + |
| 85 | + public T Data { get; set; } |
| 86 | + |
| 87 | + #endregion |
| 88 | + } |
| 89 | +} |
0 commit comments