代码之家  ›  专栏  ›  技术社区  ›  santosh singh

在.net中,在两个线程之间共享静态变量的最佳方法是什么

  •  1
  • santosh singh  · 技术社区  · 14 年前

    在.net中,在两个线程之间共享静态变量的最佳方法是什么?

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace StackOverflow
    {
    
        class ThreadStaticProgram
        {
            static string threadStaticVariable = "";
            static void Main(string[] args)
            {
    
                Console.WriteLine(" Main Thread Before {0} ", threadStaticVariable);
                threadStaticVariable = " Main Thread ";
                Console.WriteLine(" Main Thread Before For Loop = {0} ", threadStaticVariable);
                Thread[] threads = new Thread[3];
                for (int i = 0; i < 3; i++)
                {
                    threads[i] = new Thread(delegate(object j)
                    {
                        Console.WriteLine(" Thread{0} before = {1} ", j, threadStaticVariable);
                        threadStaticVariable = " Thread " + j;
                        Console.WriteLine(" Thread{0} after ={1} ", j, threadStaticVariable);
                    }
                    );
                    threads[i].Start(i);
                }
                Array.ForEach(threads, delegate(Thread t) { t.Join(); });
                Console.WriteLine(" Main Thread after For Loop = {0} ", threadStaticVariable);
                Console.ReadLine();
            }
        }
    }
    

    问题二-什么是线程本地存储?

    1 回复  |  直到 14 年前
        1
  •  1
  •   Reed Copsey    14 年前

    这取决于变量。如果它是一个可以原子设置的类型,则将其标记为volatile和/或使用联锁类更改其值。

    Interlocked.Exchange

    否则,您可能需要使用某种形式的同步。私有静态对象是最常见的选项,但这取决于它是否可以使用锁进行包装。如果是一个集合,使用 ConcurrentQueue<T> 类似的方法消除了对锁的需要。