Created
March 20, 2020 10:16
-
-
Save waf/74795695944b35dc58bc726ddd529b72 to your computer and use it in GitHub Desktop.
AsyncLocal Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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