Why thread Id changes in ASP.NET Core?

Viewed 57

I'm using Thread to store Locale and pass it down the layers.

In my middleware I set the selected locale in the current thread as follow:

Thread.SetData(Thread.GetNamedDataSlot('SelectedLocale'), selectedLocale /* I get this value form the request */);

Then in the rest of my code, I use this line to access that data:

var selectedLocale = Thread.GetData(Thread.GetNamedDataSlot('SelectedLocale'));

However, this sometimes works, and sometimes returns null.

I used var threadId = Thread.CurrentThread.ManagedThreadId and realized that Id changes sometimes.

Why is it so? How can I make sure that I'm using the same thread during my request processing?

Update

I'm using the same technique for my APIs and for my Razor Page applications.

My APIs work just fine. They never fail.

However, my Razor Page applications fail almost 70% of the time. But they also work sometimes.

I think there must be something related to the Razor Pages here.

1 Answers

I'm using Thread to store Locale and pass it down the layers.

I'm not using async/await in my code

If you're still thinking in threads and not using async/await, you're doing it wrong. Threads are too low-level of a construct to be using in application code, especially web application code.

It's all tasks and contexts now. If you use Razor pages, stuff will be handled async by the framework. Just use the HttpContext to pass entities from one middleware to the next.

Though the HttpContext has its own problems.

More reading: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0, https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-6.0.

Related