I currently have a static List of custom objects (but I've tested with a List of int as well). I'm modifying this List in 2 methods:
- Button_Click event
- System.Timers.Timer that elapses every 5 minutes
The problem is that it seems like List is initialized for both methods when the application begins and is independent. Meaning when I add an element to #1, it is not reflected in #2. I'm guessing it's because the Timers.Timer is started on a separate thread?
In which case, I have tried putting a primitive int as well. In that case, the number is changed in both and reflects one another. Is the problem due to the fact that it is a dynamic list of objects?
What would you recommend I do?
Thank you!
Sorry for not posting the code earlier! I tried with the lock recommendation, to no avail. I've never used it before so please let me know if I didn't use it correctly.
protected System.Timers.Timer fiveMinutesTimer
public static List<int> listInt = new List<int>();
public static int counter = 0;
public override void OnLoginCompleted()
{
fiveMinutesTimer = new System.Timers.Timer();
fiveMinutesTimer.Interval = 300000;
fiveMinutesTimer.Elapsed += (sender, e) => OnFiveMinutesTimerElapsed(sender, e, EChatEntryType.ChatMsg);
fiveMinutesTimer.Enabled = true;
}
public override void OnMessage(string message, EChatEntryType type)
{
//lock (listInt)
//{
listInt.Add(3);
listInt.Add(3);
listInt.Add(3);
counter += 3;
Console.WriteLine("OnMessage: " + listInt.Count);
Console.WriteLine("OnMessage int: " + counter);
//}
}
private void OnFiveMinutesTimerElapsed(object source, System.Timers.ElapsedEventArgs e, EChatEntryType type)
{
//lock (listInt)
//{
listInt.Add(3);
counter++;
Console.WriteLine("Timer: " + listInt.Count);
Console.WriteLine("Timer int: " + counter);
//}
}
Triggering OnMessage at 4:59
OnMessage: 3
OnMessage int: 3
OnFiveMinutesTimerElapsed
Timer: 1
Timer int: 4
Triggering OnMessage at 9:59
OnMessage: 6
OnMessage int: 7
OnFiveMinutesTimerElapsed
Timer: 2
Timer int: 8