它是根据@AndrewSilver 建议解决的,将共享变量放在单独的文件中:
public static class AK_Configs
{
public static bool notOK = false;
public static object _lock = new object();
public static Flags flags = new Flags();
public static Random random = new Random();
public static int countInc = 0;
public static int countDec = 0;
public static int countCheck = 0;
}
public class Flags
{
public int I { get; set; }
public int J { get; set; }
public override string ToString()
{
return $"I={I},J={J}";
}
}
程序:
services.AddHostedService<Worker1>();//read/wite Worker
services.AddHostedService<Worker2>();//read/wite Worker
services.AddHostedService<Worker3>();//readonly Worker
Worker1:增加 I 和 J
while (!stoppingToken.IsCancellationRequested)
{
lock (AK_Configs._lock)
{
AK_Configs.countInc++;
Thread.Sleep(AK_Configs.random.Next(10) * 100);
AK_Configs.flags.I++;
Thread.Sleep(AK_Configs.random.Next(10) * 100);
AK_Configs.flags.J++;
_logger.LogInformation($"===Increase {AK_Configs.countInc}:{AK_Configs.flags}");
}
await Task.Delay(15, stoppingToken);
}
Work2:同时减少 I 和 J
while (!stoppingToken.IsCancellationRequested)
{
lock (AK_Configs._lock)
{
AK_Configs.countDec++;
Thread.Sleep(AK_Configs.random.Next(10)*100);
AK_Configs.flags.I--;
Thread.Sleep(AK_Configs.random.Next(10)*100);
AK_Configs.flags.J--;
_logger.LogInformation($"---Decrease {AK_Configs.countDec}:{AK_Configs.flags}");
}
await Task.Delay(15, stoppingToken);
}
Worker3:只读并注意数据不一致
while (!stoppingToken.IsCancellationRequested)
{
lock (AK_Configs._lock)
{
AK_Configs.countCheck++;
if (AK_Configs.flags.I != AK_Configs.flags.J)
{
_logger.LogInformation("Data corrupted! flags:" + (AK_Configs.flags));
_appLifetime.StopApplication();
}
}
await Task.Delay(15, stoppingToken);
}