Skip to content

Instantly share code, notes, and snippets.

@waf
Created March 20, 2020 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waf/74795695944b35dc58bc726ddd529b72 to your computer and use it in GitHub Desktop.
Save waf/74795695944b35dc58bc726ddd529b72 to your computer and use it in GitHub Desktop.
AsyncLocal Demo
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncLocalPlayground
{
class Program
{
//private static string ThreadId; // too wide! per AppDomain
//private static ThreadLocal<string> ThreadId = new ThreadLocal<string>(); // too narrow! per thread, await involves different threads.
private static AsyncLocal<string> ThreadId = new AsyncLocal<string>(); // per async flow
public static void Main()
{
var threads = new[] { "api-request1", "api-request2", "api-request3" }
.Select(threadId =>
{
// pretend this is a webserver e.g. IIS
var t = new Thread(async () =>
{
ThreadId.Value = threadId;
// pretend this is our executing asp.net code
var tasks = new[] { "a", "b", "c" }.Select(taskId => DoWork(taskId));
await Task.WhenAll(tasks);
});
t.Start();
return t;
})
.ToList();
Console.ReadKey();
}
private static async Task DoWork(string taskId)
{
await Task.Delay(10);
Console.WriteLine(ThreadId.Value + ":" + taskId);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment