ThreadStatic field VS method parameter VS one instance per thread

679 Views Asked by At

Im working on a multithreaded application, therefore, I was always trying not to use private fields that may raise a conflict in the type instance i was using in different threads. Instead, I have been hauling information i needed to work as method parameters. This led to dozens of methods that all declared the same parameters:

private void MySubmethod(MyConfiguration configuration)

Now i was thinking to redesign the type and creating one instance per thread working, but then i stumbled upon the ThreadStatic attribute.

Is it a good idea to just declare a private threadstatic field, initialize it inside the main method each thread is calling and reuse this field inside all sub-methods, rendering the parameter obsolete? Or has it any drawbacks, so that i rather should concentrate on creating a new instance per Thread?

[ThreadStatic]
private static MyConfiguration _configuration;
1

There are 1 best solutions below

1
Marc Gravell On BEST ANSWER

Is it a good idea to just declare a private threadstatic field, initialize it inside the main method each thread is calling and reuse this field inside all sub-methods, rendering the parameter obsolete?

No, it is not; it means that any code that touches threads is now deeply unreliable; and with things like ThreadPool, the TPL and async/await, threads are inevitable in modern applications (even if they are implicit rather than explicit in your code). Variables that are thread-dependent are also hugely problematic to debug. Unless there is a very good reason, my advice would be to retain the over-arching context, or plug into an existing robust implementation. For example, in a web application you might reasonably access the current request via the static methods - but even that you need to be careful to know whether you are on the request thread, vs on a worker thread that should have had everything it needed to know handed to it on a plate.