C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#的AsnycLocal与ThreadLocal

浅析C#中的AsnycLocal与ThreadLocal

作者:沉默的雪糕

这篇文章主要给大家介绍了关于C#中AsnycLocal与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

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

总结

到此这篇关于C#中AsnycLocal与ThreadLocal的文章就介绍到这了,更多相关C#的AsnycLocal与ThreadLocal内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文