gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:49:27 24 4
gpt4 key购买 nike

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

代码如下:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com