【问题标题】:Static C# list keeps growing in size after each iteration每次迭代后,静态 C# 列表的大小都会不断增长
【发布时间】:2023-03-06 03:00:01
【问题描述】:

我目前正在尝试调试每 5 分钟运行一次的程序。我的主要问题是试图找到每次我的程序运行时静态列表不断增长的原因。目标是保持此列表的大小相同,但每次执行时都会使用不同的值更新它的项目。

下面是该类的代码,该类每 5 分钟运行一次,并为我发送给 rabbitmq 的 json 消息设置值。

PushJsonToBroker() 方法是我发现每次执行后compDataList 的大小都会增加的问题。

class Program
{
        private static List<SimulatedData> compDataList = new List<SimulatedData>();

        public static void Main(String[] args)
        {
            var autoEvent = new AutoResetEvent(false);
            var stateTime = new Timer(SimulateData, autoEvent, 1000, 300000);
            Console.ReadKey();
        }

        public static void SimulateData(object state)
        {
            Console.WriteLine("\n" + DateTime.Now + "\nSimulating Data...");
            List<string> compValueList = new List<string>();
            compValueList = ReadCompValueRow();
            CompChannelValueMatching(compValueList);
            PushJsonToBroker();
        }

        public static void CompChannelValueMatching(List<string> compValueList)
        {
            try
            {
                Console.WriteLine("Matching values with channels for Compressor...");
                foreach(var c in compChannelListMongo)
                {
                    string value;
                    string units;
                    string simTag;
                    string name;
                    var channelIndexMongo = compChannelListMongo.IndexOf(c);
                    if (c.Equals("C1"))
                    {
                        value = compValueList.ElementAt<string>(0);
                        units = compUnitListMongo.ElementAt<string>(channelIndexMongo);
                        simTag = compTagListMongo.ElementAt<string>(channelIndexMongo);
                        name = compNameListMongo.ElementAt<string>(channelIndexMongo);
                        decimal num, x;
                        if (decimal.TryParse(value, out x))
                        {
                            num = x;
                        }
                        else
                        {
                            num = 0;
                        }
                        SetCompValues(units, simTag, name, num);
                    }
               }
               catch (Exception ex)
               {
                   Console.WriteLine(ex);
               }
        }

    public static void SetCompValues(string units, string simTag, string name, decimal num)
    {
        compDataList.Add(new SimulatedData { units = units, tag = simTag, name = name, value = num });
    }

    public static void PushJsonToBroker()
    {
        List<string> thingList = new List<string>();
        List<string> assetTypeList = new List<string>();
        Simulator.JsonProps data = new Simulator.JsonProps();
        DateTime dateTime = DateTime.Now;
        var dateValue = dateTime.ToString("yyyyMMddhhmmss.ffffff");
        var demoThings = DBConnect.CosmosClient.GetCollection<BsonDocument>("Things");

        foreach (var doc in demoThings.Find(x => x["_id"] != "").ToList())
        {
            thingList.Add(doc["_id"].ToString());
            assetTypeList.Add(doc["AssetType"].ToString());
        }
        try
        {
            Console.WriteLine("\nCreating Json...");
            foreach (var thingNo in thingList)
            {
                var thingIndex = thingList.IndexOf(thingNo);
                var assetType = assetTypeList.ElementAt<string>(thingIndex);
                if (assetType.Equals("HSE"))
                {
                    data = new Simulator.JsonProps
                    {
                        machineId = thingNo,
                        trendValues = hseDataList.ToArray(),
                        messageId = dateValue + "@" + thingNo,
                        scheduleDate = DateTime.UtcNow
                    };
                }
                if(assetType.Equals("Spotlight_Comp"))
                {
                    data = new Simulator.JsonProps
                    {
                        machineId = thingNo,
                        trendValues = compDataList.ToArray(), //problem is here!, every time the program runs the list grows in size instead of staying the same size each time it executes
                        messageId = dateValue + "@" + thingNo,
                        scheduleDate = DateTime.UtcNow
                    };
                }
                if(assetType.Equals("CPI"))
                {
                    data = new Simulator.JsonProps
                    {
                        machineId = thingNo,
                        trendValues = cpiDataList.ToArray(),
                        messageId = dateValue + "@" + thingNo,
                        scheduleDate = DateTime.UtcNow
                    };
                }
                string jsonOutput = JsonConvert.SerializeObject(data, Formatting.Indented);
                Console.WriteLine("Publishing JSON to broker for " + assetType);

                switch (assetType)
                {
                    case "Spotlight_Comp":
                        tcompChannel.BasicPublish(exchange: "DataEx",
                                         routingKey: "",
                                         basicProperties: null,
                                         body: Encoding.UTF8.GetBytes(jsonOutput));
                        break;
                    case "HSE":
                        thseChannel.BasicPublish(exchange: "DataEx",
                                         routingKey: "",
                                         basicProperties: null,
                                         body: Encoding.UTF8.GetBytes(jsonOutput));
                        break;
                    case "CPI":
                        tcpiChannel.BasicPublish(exchange: "DataEx",
                                         routingKey: "",
                                         basicProperties: null,
                                         body: Encoding.UTF8.GetBytes(jsonOutput));
                        break;

                }

                Console.WriteLine("Done publishing...");

            }
            Console.WriteLine("Done sending data for all assets..." + "\nWaiting to run again...");

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}

下面是接收将在 json 消息中使用的值的类的代码。

    public class Simulator
    {

        public class JsonProps
        {
            public string machineId { get; set; }
            public SimulatedData[] trendValues { get; set; }
            public string messageId { get; set; }
            public DateTime scheduleDate { get; set; }
        }
        public class SimulatedData
        {
            public decimal value { get; set; }
            public string units { get; set; }
            public string tag { get; set; }
            public string name { get; set; }
        }

    }

我不确定问题是否与列表是否为静态有关。但老实说,这个问题让我很难过。如果有人对如何运行该程序并保持列表大小相同但在每次执行后具有不同的值有一些意见或指导,这将极大地帮助我!

【问题讨论】:

  • SetCompValues 不断通过.Add 向static 列表添加更多项目,这就是您的列表不断增长的原因,您在调用之前从未Clear() 或将其设置为new List() SetCompValues
  • 我会推荐 new List() 而不是 Clear().. 当您有其他变量引用它时会导致更多问题
  • 所以当我调用 CompChannelValueMatching() 时,我应该使用 compDataList = new List();

标签: c# arrays json arraylist static


【解决方案1】:

在你得到数组之后,清除列表

data = new Simulator.JsonProps
{
    machineId = thingNo,
    trendValues = compDataList.ToArray(), //problem is here!, every time the program runs the list grows in size instead of staying the same size each time it executes
    messageId = dateValue + "@" + thingNo,
    scheduleDate = DateTime.UtcNow
};
compDataList.Clear(); //add this to resolve your Problem

【讨论】:

  • 我想我喜欢 compDataList.Clear() 方法。而不必声明一个新的 List();
猜你喜欢
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 2020-01-04
  • 1970-01-01
相关资源
最近更新 更多