According to the Microsoft Docs, the attribute ThreadStatic
"indicates that the value of a static field will be unique to each thread".
And from what I read in this article from a blog of Microsoft itself:
ASP.NET Thread Usage on IIS 7.5, IIS 7.0, and IIS 6.0 - Thomas Marquardt’s Blog
https://blogs.msdn.microsoft.com/tmarq/2007/07/20/asp-net-thread-usage-on-iis-7-5-iis-7-0-and-iis-6-0/
I understood that requests in ASP.NET can use the same thread but can also be executed in different threads. So it seems to me that what’s happening is that in your tests some threads are created, and each one has its value for the static field HomeController.texto
, because of the attribute ThreadStatic
.
Here in this discussion in an MSDN forum:
[Threadstatic] and the threadpool - MSDN Forums
https://social.msdn.microsoft.com/Forums/vstudio/en-US/3d464b27-ac8c-4800-9d23-d8ddadb41931/
moderator Reed Copsey Jr suggests class use ThreadLocal<T>
(documentation), instead of the attribute ThreadStatic
. And, using the example of documentation, you can even create a new static field in your class HomeController
to check if the threads are really different:
public class HomeController : Controller {
[ThreadStatic] public static String texto;
// Variável Thread-Local que produz um nome para uma thread.
public static readonly ThreadLocal<string> NomeThread = new ThreadLocal<string>(() =>
{
return $"Thread #{Thread.CurrentThread.ManagedThreadId}";
});
public String teste(String valor) {
// Substitui as duas verificações anteriores pelo método String.IsNullOrEmpty().
if(String.IsNullOrEmpty(valor)) {
texto = valor;
}
return $"Texto: '{texto}' / Nome da thread: '{NomeThread}'";
}
}
You could also simply delete the attribute ThreadStatic
of that field, if you wanted a unique value for the entire application, because according to this OS responseEN, static fields are thread-safe:
c# - Thread Safety on readonly Static field initialisation - Stack Overflow
https://stackoverflow.com/a/12159883/8133067
But, why don’t you leave this field as a normal field instead of static? That way each object HomeController
would have its value, no?
Pool is not being recycled?
– Leandro Angelo
So @Leandroangelo started Monday the application works already more than a month ago. No configuration modified.
– Hiago Souza
Are you using IIS? Already tried to restart the application?
– Pedro Gaspar
@Pedrogaspar yes, I tried. But it did not roll, it is a Multitenancy application at the moment we are making efforts to use Token direct in Request.
– Hiago Souza