在处理多线程应用程序时,我曾经遇到过需要为静态字段赋值的场景。我想在所有其余线程中使用静态字段的最新值。
代码如下所示:
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
请给我任何想法。
提前致谢!