亲宝软件园·资讯

展开

C#的AsnycLocal与ThreadLocal 浅析C#中的AsnycLocal与ThreadLocal

沉默的雪糕 人气:0
想了解浅析C#中的AsnycLocal与ThreadLocal的相关内容吗,沉默的雪糕在本文为您仔细讲解C#的AsnycLocal与ThreadLocal的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:asnyclocal与threadlocal,c#,asnycLocal,c#,threadlocal,下面大家一起来学习吧。

AsnyncLocal与ThreadLocal都是存储线程上下文的变量,但是,在实际使用过程中两者又有区别主要的表现在:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace await_aysnc
{
    class Program
    {
        static ThreadLocal<int> ThreadObj = new ThreadLocal<int>();
        static AsyncLocal<int> AsyncObj = new AsyncLocal<int>();

        static void Main(string[] args)
        {
            AsyncObj.Value = 1;
            ThreadObj.Value = 1;
            Console.WriteLine($"Task执行前:AsyncObj= {AsyncObj.Value} ThreadObj= {ThreadObj.Value} ThreeadId = {Thread.CurrentThread.ManagedThreadId}");
            Task.Run(async() =>
            {
                Console.WriteLine($"RunAsync异步执行前:AsyncObj= {AsyncObj.Value} ThreadObj= {ThreadObj.Value} ThreeadId = {Thread.CurrentThread.ManagedThreadId}");
                await RunAsync();
                Console.WriteLine($"RunAsync异步执行后:AsyncObj = {AsyncObj.Value} ThreadObj= {ThreadObj.Value} ThreeadId = {Thread.CurrentThread.ManagedThreadId}");
            });
            Console.WriteLine($"Task执行后:AsyncObj= {AsyncObj.Value} ThreadObj= {ThreadObj.Value} ThreeadId = {Thread.CurrentThread.ManagedThreadId}");
            Console.Read();
        }

        static async Task RunAsync()
        {           
            Console.WriteLine($"Delay异步执行前:AsyncObj = {AsyncObj.Value} ThreadObj= {ThreadObj.Value} ThreeadId = {Thread.CurrentThread.ManagedThreadId} ");
            AsyncObj.Value = 2;
            ThreadObj.Value = 2;
            await Task.Delay(100);
            Console.WriteLine($"Delay异步执行后:AsyncObj = {AsyncObj.Value} ThreadObj= {ThreadObj.Value} ThreeadId = {Thread.CurrentThread.ManagedThreadId}");
        }
    }

}

Task执行前:AsyncObj= 1 ThreadObj= 1 ThreeadId = 1
Task执行后:AsyncObj= 1 ThreadObj= 1 ThreeadId = 1
RunAsync异步执行前:AsyncObj= 1 ThreadObj= 0 ThreeadId = 3
Delay异步执行前:AsyncObj = 1 ThreadObj= 0 ThreeadId = 3
Delay异步执行后:AsyncObj = 2 ThreadObj= 0 ThreeadId = 4
RunAsync异步执行后:AsyncObj = 1 ThreadObj= 0 ThreeadId = 4

从结果上可以看出一下结论:

总结

加载全部内容

相关教程
猜你喜欢
用户评论