如何在整个应用程序中实现全局int/counter ?

本文关键字:int 全局 counter 实现 应用程序 | 更新日期: 2023-09-27 18:06:23

这对其他人来说可能是显而易见的,我已经纠结了几个小时了,但无济于事。

如何在整个应用程序中实现全局int/counter ?

这只是我需要的一个int值,它只会一直增加。计数器将从不同类中的几个不同方法异步调用,这些方法都对来自webApi的相同JSon输出做出贡献。有很多小块的数据需要一个唯一的id附加到它们。

希望这是有意义的。谢谢你的帮助。

如何在整个应用程序中实现全局int/counter ?

public static Global
{
    private static int _counter = 0;
    private static readonly object _lockObject = new object();
    public static void Increment()
    {
        lock (_lockObject) {
            _counter++;
        }
    }
    public static int Counter
    {
        get
        {
            lock (lockObject) {
                return _counter;
            }
        }
    }
}
public static class Global 
{
    private static int counter = 0;
    public static int Counter
    {
         get
         {
             return Interlocked.Increment(ref counter);
         {
    }
}