本文整理汇总了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();
}
}
输出:
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 ''