Skip to main content

[Code refactoring] ThreadStatic and NULL checks


ThreadStatic is used when you have content that needs to be static per thread. For example we can have a field that needs to be static per thread and not per application. In the example below we can see that _message field is decorated with ThreadStatic attribute. Each thread will have a different instance of this field.
public class Foo
{
  [ThreadStatic] 
  private static string _messageBuffer;
}
Great, until now we are good. But scrolling some lines below we find the following code:
public class Foo
{
  [ThreadStatic] 
  private static string _messageBuffer;
  
  public void DoSomeAction(string input)
  {
    if ( _messageBuffer == null )
    {
      _messageBuffer = string.Empty;
    }
    _messageBuffer += input;
  }
  
  public void DoMoreAction(string input)
  {
    if ( _messageBuffer == null )
    {
      _messageBuffer = string.Empty;
    }
    _messageBuffer += " " + input;
  }
...
}
This is not good. Why would you like to check at each call if the field is initialized or not. We refactor this as follow:
public class Foo
{
  [ThreadStatic] 
  private static string _messageBuffer = string.Empty;  
  
  public void DoSomeAction(string input)
  {
    _messageBuffer += input;
  }
  
  public void DoMoreAction(string input)
  {
    _messageBuffer += " " + input;
  }
}
Or we could add a static constructor. But surprise (!!!), when our methods are called we get NullReferenceException on our thread static filed. Surprised? Well, we check the code and we see that we initialize the field. But, the initialization is called only on one thread. Because of this, on the rest of the threads the field is not initialized.
Now we understood why the check of null was made on each method. We know the cause, but the old solution was not so good at all.
A solution for our problem would be to create a wrapper property over our field. We need only the getter that can check if the field is initialize or not. In this way the null check will exist only in one location.
public class Foo
{
  [ThreadStatic] 
  private static string _messageBuffer;
  
  private static string MessageBuffer
  {
    get
    {
      if ( _messageBuffer == null )
      {
        _messageBuffer = string.Empty;
      }
      
      return _messageBuffer;
    }
  }
  
  public void DoSomeAction(string input)
  {    
    MessageBuffer += input;
  }
  
  public void DoMoreAction(string input)
  {
    MessageBuffer += " " + input;
  }
}
We don't need a lock when we initialize the field because is unique per thread. This means that two different threads will have two different instance of this object.
If we have more fields that are thread static, we can add a Boolean that check if the thread static fields were initialized. In this way all the fields would be initialize from one shot.
public class Foo
{
  [ThreadStatic] 
  private static string _messageBuffer;
  [ThreadStatic] 
  private static int _messageCount;   
  [ThreadStatic] 
  private static StatusState _currentState;  
  [ThreadStatic] 
  private static bool _isInitialized = false;
  
  private static InitializePerThreadContent()
  {
    _messageBuffer = string.Empty;
    _messageCount = 1;
    _currentState = StatusState.Empty;
    _isInitialized = true;
  }
  
  private static string MessageBuffer
  {
    get
    {
      if ( !_isInitialized )
      {
        InitializePerThreadContent();
      }
      
      return _messageBuffer;
    }
  }
  
  private static string MessageCount
  {
    get
    {
      if ( !_isInitialized )
      {
        InitializePerThreadContent();
      }
      
      return _messageCount;
    }
  }
  
    private static string CurrentState
  {
    get
    {
      if ( !_isInitialized )
      {
        InitializePerThreadContent();
      }
      
      return _currentState;
    }
  }
  
  ...
}

Comments

  1. An alternative for your solution would be the use of the System.Threading.ThreadLocal class, present inside .NET framework since version 4.0.

    ReplyDelete

Post a Comment

Popular posts from this blog

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Run native .NET application in Docker (.NET Framework 4.6.2)

Scope
The main scope of this post is to see how we can run a legacy application written in .NET Framework in Docker.

Context
First of all, let’s define what is a legacy application in our context. By a legacy application we understand an application that runs .NET Framework 3.5 or higher in a production environment where we don’t have any more the people or documentation that would help us to understand what is happening behind the scene.
In this scenarios, you might want to migrate the current solution from a standard environment to Docker. There are many advantages for such a migration, like:

Continuous DeploymentTestingIsolationSecurity at container levelVersioning ControlEnvironment Standardization
Until now, we didn’t had the possibility to run a .NET application in Docker. With .NET Core, there was support for .NET Core in Docker, but migration from a full .NET framework to .NET Core can be costly and even impossible. Not only because of lack of features, but also because once you…