当前位置: 首页>>代码示例>>C#>>正文


C# AsyncLocal<T>类代码示例

本文整理汇总了C#中System.Threading.AsyncLocal<T>的典型用法代码示例。如果您正苦于以下问题:C# AsyncLocal<T>类的具体用法?C# AsyncLocal<T>怎么用?C# AsyncLocal<T>使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


AsyncLocal<T>类属于System.Threading命名空间,在下文中一共展示了AsyncLocal<T>类的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AsyncMethodA

//引入命名空间
using System;
using System.Threading;
using System.Threading.Tasks;

class Example
{
    static AsyncLocal<string> _asyncLocalString = new AsyncLocal<string>();

    static ThreadLocal<string> _threadLocalString = new ThreadLocal<string>();

    static async Task AsyncMethodA()
    {
        // Start multiple async method calls, with different AsyncLocal values.
        // We also set ThreadLocal values, to demonstrate how the two mechanisms differ.
        _asyncLocalString.Value = "Value 1";
        _threadLocalString.Value = "Value 1";
        var t1 = AsyncMethodB("Value 1");

        _asyncLocalString.Value = "Value 2";
        _threadLocalString.Value = "Value 2";
        var t2 = AsyncMethodB("Value 2");

        // Await both calls
        await t1;
        await t2;
     }

    static async Task AsyncMethodB(string expectedValue)
    {
        Console.WriteLine("Entering AsyncMethodB.");
        Console.WriteLine("   Expected '{0}', AsyncLocal value is '{1}', ThreadLocal value is '{2}'", 
                          expectedValue, _asyncLocalString.Value, _threadLocalString.Value);
        await Task.Delay(100);
        Console.WriteLine("Exiting AsyncMethodB.");
        Console.WriteLine("   Expected '{0}', got '{1}', ThreadLocal value is '{2}'", 
                          expectedValue, _asyncLocalString.Value, _threadLocalString.Value);
    }

    static async Task Main(string[] args)
    {
        await AsyncMethodA();
    }
}
开发者ID:.NET开发者,项目名称:System.Threading,代码行数:44,代码来源:AsyncLocal

输出:

Entering AsyncMethodB.
Expected 'Value 1', AsyncLocal value is 'Value 1', ThreadLocal value is 'Value 1'
Entering AsyncMethodB.
Expected 'Value 2', AsyncLocal value is 'Value 2', ThreadLocal value is 'Value 2'
Exiting AsyncMethodB.
Expected 'Value 2', got 'Value 2', ThreadLocal value is ''
Exiting AsyncMethodB.
Expected 'Value 1', got 'Value 1', ThreadLocal value is ''


注:本文中的System.Threading.AsyncLocal<T>类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。