sachin
sachin

Reputation: 15

How to store variables on a thread?

I have a method that is running on a single thread currently. In this method I am storing variables using HTTPContext.Current.Session["VariableName"] = "VariableValue"

But now I want to run the same method above on multiple threads in parallel. For obvious reason I will not able to store my variables using above statement. Now I need to store such variables privately within single thread using same variable names. For Example

Thread1 ValueofVar = "xyz"; Thread2 ValueofVar = "abc"; Thread3 ValueofVar = "jkl";

Kindly suggest suitable solution to this issue that I am facing ?

Upvotes: 0

Views: 687

Answers (1)

Yair Nevet
Yair Nevet

Reputation: 13003

You can use a Thread-Level storage constructs for your variables, by which, your variables data will be only available on the scope of a Thread - for that, use either ThreadStatic or ThreadLocal (.NET 4 and up).

Example of ThreadLocal:

using System;
using System.Threading;
using System.Threading.Tasks;

class ThreadLocalDemo
{
            static void Main()
        {
            ThreadLocal<string> ThreadName = new ThreadLocal<string>(() =>
            {
                return "Thread" + Thread.CurrentThread.ManagedThreadId;
            });

            Action action = () =>
            {
                bool repeat = ThreadName.IsValueCreated;

                Console.WriteLine("ThreadName = {0} {1}", ThreadName.Value, repeat ? "(repeat)" : "");
            };
            Parallel.Invoke(action, action, action, action, action, action, action, action);

            ThreadName.Dispose();
        }
}

Upvotes: 1

Related Questions