Problem with C#Threadstatic

Asked

Viewed 107 times

0

I own a system where his authentication keeps a token in a Threadstatic property. It turns out that Monday, he started distributing the tokens incorrectly (after windows server update).

I made the application below to test the scenario

public class HomeController : Controller {
    [ThreadStatic]
    public static String texto;

    public String teste(String valor) {
        if(valor != null && !valor.equals("")) {
             texto = valor;
        }
        return texto;
    }
}

Setting

If I call the URL http://localhost/home/teste?valor=oi i get the result hi. If I call the same method http://localhost/home/teste without passing the time value attribute it returns me empty, time it returns me filled and if I call again passing as value tchau it will keep returning this value to me randomly. This behavior is normal with the ThreadStatic or you may have modified something in the . NET update?

Thank you.

  • Pool is not being recycled?

  • So @Leandroangelo started Monday the application works already more than a month ago. No configuration modified.

  • Are you using IIS? Already tried to restart the application?

  • @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.

2 answers

0

Yes, that’s normal behavior

You don’t control which thread runs your Controller. Each request can have a new thread, a repeated thread, and you have no way of knowing.

How to solve

To save a user-specific data, you use sessions.

0

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?

  • Hello Peter, then. In fact the application is separated into 16 classLibrary, and one of those classLibrary is Business. The Business Library uses another classLibrary to Auth, today the business layer needs to know who is the user who is executing the action. It’s not just a webapi, it has windows services and other things involved. But recently there was this problem, which coincided with the update of .NET. Because the same day he updated the problem happened to occur. But you’re right, it’s not the ideal solution to identify an action with static attributes even in threads.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.