【发布时间】:2022-12-01 18:08:13
【问题描述】:
So I have this piece of code, but it's not working as expected. You can copy and paste it and try it yourself.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Helper
{
public static class Program
{
public static bool active = false;
public static WorldData wdataTest = new WorldData(); // Simple test objects
public static Dictionary<string, WorldData> dic = new Dictionary<string, WorldData>();
public static void Main()
{
active = true;
Start();
}
public static void Start()
{
dic.Add("test", wdataTest);
System.Timers.Timer timer = new System.Timers.Timer();
string serialized;
bool loaded = false;
int i = -10;
int normalizedRate = 2;
timer.Interval = 100;
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler((_, __) => {
try
{
Stopwatch st = new Stopwatch();
st.Start();
if (active)
{
if (loaded)
{
i++;
}
foreach (WorldData wData in dic.Values)
{
loaded = true;
foreach (EntityList collection in wData.collectionOfCollections)
{
serialized = JsonConvert.SerializeObject(collection.Entities);
// Does some other things
if (i == normalizedRate)
{
WriteSerialized(collection, serialized);
i = 0;
}
}
}
}
st.Stop();
Console.WriteLine(st.ElapsedMilliseconds.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
});
timer.Enabled = true;
Console.ReadKey();
}
public static void WriteSerialized(EntityList collection, string serializedObj)
{
Console.WriteLine(collection.Name);
// Write to file serializedObj
}
public class WorldData
{
public List<EntityList> collectionOfCollections;
public WorldData()
{
collectionOfCollections = new List<EntityList>();
collectionOfCollections.Add(new EntityList("hammers"));
collectionOfCollections.Add(new EntityList("screwdrivers"));
collectionOfCollections.Add(new EntityList("nails"));
collectionOfCollections.Add(new EntityList("pcs"));
}
}
public class EntityList
{
public List<object> Entities;
public string Name { get; set; }
public EntityList(string name)
{
Name = name;
Entities = new List<object>();
Entities.Add(new object());
}
}
}
}
The code purpose is to serialize all those objects every 100ms to send to another program, and every 200ms write the serialized object to file for replay purposes (I have another piece of code that reads the files again later). I found out the bug after only a file had something written on it, so I used the Console.WriteLine to make sure it iterated over every collection. What I got is only "hammers" and 0 printed. I can believe it takes less than 1ms to complete the event in this example, but in my real application it has to serialize big objects and I have the same results. Hammers and 0. I put a breakpoint to debug it and checked that the collections are properly filled...what am I getting wrong?
EDIT: As per request I explained the purposes of the program in deeper details.
【问题讨论】:
-
It's great that you've provided a complete example - but do you really need nearly 100 lines of code to demonstrate the problem? Is JSON serialization actually required as part of demonstrating this? What is the code intended to do? ("Print out all the collection names" is far too brief a description for something involving serialization, timers etc.)
-
Note that after printing out asinglecollection, you're changing the value of
i... why are you doing that? Why are you only sometimes printing things out in the first place? There's a lot that's unclear about the code in this question. -
I'm deeply suspicious of a short interval timer and a whole load of variables being captured (and therefore shared) in the lambda. What are you actually trying to do here other than give yourself reentrancy headaches?
-
after the first run
i = 0;and never changes. -
Thanks @JonSkeet for helping me become a better StackOverflower comment after comment.