简体   繁体   English

如何在线程上存储变量?

[英]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" 在这种方法中,我使用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 ? 请为我面临的这个问题提出合适的解决方案?

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). 您可以为变量使用线程级存储构造,这样,变量数据将仅在Thread范围内可用-为此,请使用ThreadStaticThreadLocal (.NET 4及更高版本)。

Example of ThreadLocal : 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();
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM