c# - 设置一次静态字段值并在所有其他线程中使用最新设置的值

标签 c# multithreading thread-safety

在处理多线程应用程序时,我曾经遇到过需要为静态字段赋值的情况。我想在所有其余线程中使用静态字段的最新值。

代码如下:

Main() 方法:

for (var i = 1; i <= 50; i++)
{
  ProcessEmployee processEmployee = new ProcessEmployee();

  Thread thread = new Thread(processEmployee.Process);
  thread.Start(i);
}

public class ProcessEmployee
    {
        public void Process(object s)
        {

            // Sometimes I get value 0 even if the value set to 1 by other thread.
            // Want to resolve this issue.
            if (StaticContainer.LastValue == 0)
            {
                Console.WriteLine("Last value is 0");

            }

            if (Convert.ToInt32(s) == 5)
            {
                StaticContainer.LastValue = 1;
                Console.WriteLine("Last Value is set to 1");
            }

            // Expectation: want to get last value = 1 in all rest of the threads. 
            Console.WriteLine(StaticContainer.LastValue);
        }
    }

public static class StaticContainer
    {
        private static int lastValue = 0;

        public static int LastValue
        {
            get
            {
                return lastValue;
            }
            set
            {
                lastValue = value;
            }
        }
    }

问题:

基本上,我想知道,一旦我通过任何线程为静态字段设置特定值,我想获得相同的值(另一个thread设置的最新值) )始终在 threads 的其余部分中。

请告诉我对此的任何想法。

提前致谢!

最佳答案

Basically, I want to know that once I set specific value to static field by any thread, I want to get the same value (latest value set by another thread) in rest of the threads always.

听起来你基本上错过了一个内存障碍。您可以使用显式屏障但不使用锁来解决这个问题 - 或者您可以采用强力锁定方法,或者您可以使用Interlocked:

private static int lastValue;

public int LastValue
{
    // This won't actually change the value - basically if the value *was* 0,
    // it gets set to 0 (no change). If the value *wasn't* 0, it doesn't get
    // changed either.
    get { return Interlocked.CompareExchange(ref lastValue, 0, 0); }

    // This will definitely change the value - we ignore the return value, because
    // we don't need it.
    set { Interlocked.Exchange(ref lastValue, value); }
}

可以按照newStackExchangeInstance在评论中的建议使用 volatile - 但我实际上不确定我完全理解确切它的含义,我强烈怀疑它的含义并不像大多数人所认为的那样,或者确实与 MSDN 文档所述的那样。您可能想阅读Joe Duffy's blog post on it ( and this one too ) 了解更多背景信息。

关于c# - 设置一次静态字段值并在所有其他线程中使用最新设置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17349342/

相关文章:

c# - 具有唯一连续值的线程安全方式

c# - 什么是 WPF,它与 WinForms 相比如何?

java - 我编写了以下程序,用于在线程的帮助下用java创建动画。但它给o/p作为透明窗口

c# - 删除字符串中特定字符后的字符,然后删除子字符串?

c# - 为什么 DateTime.Now 需要线程安全?

python - 不阻塞地轮询子进程对象

java - HttpSession 线程安全吗,设置/获取属性线程安全操作吗?

wpf - 在 WPF 中设置同步对象

c# - 如何将 linq var 数据类型传递给方法?

c# - winform 本地化为阿拉伯语并更改对齐方式