13

I need to share a value between threads without exceeding it's boundary. Does a static variable do this?

1
  • 3
    What do you mean by "without exceeding its boundary?" Commented Mar 22, 2011 at 16:50

5 Answers 5

12

Static variables are shared across multiple threads within an AppDomain. All threads will see, and act, upon the same instance of a static variable. As such, if you're using static, you will likely want to use some form of synchronization to protect the access of that variable.

If you want to have a thread-local variable, the ThreadLocal<T> class makes this easy. It provides a means of generating and using data that is unique per thread.

Sign up to request clarification or add additional context in comments.

Comments

12

You mean you want the variable to be thread-local?

You can either use the [ThreadStatic] attribute or the ThreadLocal<T> class from .NET 4.

Personally I'd prefer ThreadLocal<T> if you are using .NET 4 - but better still would be to avoid this sort of context if you can. Can you encapsulate the information into an instance which is used to start the thread, for example?

3 Comments

@Gik25: I would still try to design your code so it didn't rely on this. It will be clearer and easier to test if you explicitly give each object its context.
I've got a multithreaded application where every thread is dedicated to the elaboration of a set of input data that now are accessible as follow: FornituraHelper dati_fornitura = workflow.TemporaryData["Fornitura"] as FornituraHelper; My purpose is to easily access this data as follow: FornituraHelper dati_fornitura = TemporaryData.Fornitura; TemporaryData.Fornitura would be static, like Transaction.Current its shared all over the workflow. But since every thread executes a different WKF it must not overcome thread's limit (the ideal would be to be local to the WKF).
@Gik25: As I've said, you could use thread-locals for that, but I personally wouldn't. I would give each processing task the context explicitly.
3

You decorate it with the ThreadStaticAttribute, to make the static variable share across only the thread it is initialized in.

Static variables by default are across all threads in an AppDomain.

Comments

2

Yes, apply theThreadStaticAttribute

Comments

0

Yes You need to watch out for synchronization though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.