Home > Net >  C# Previous object is overwritted when adding new object to list
C# Previous object is overwritted when adding new object to list

Time:05-21

When I am adding new Timer to _timers it is overwriting previous one.

Console.WriteLine(_timers.Count()); is always writing 1

string.Join<string>(", ", _timers.Select(x => x.Uuid)); is returning empty string.

Here is my code:

[Group("timer")]
public class TimerHandler : ModuleBase<SocketCommandContext>
{
    private List<Timer> _timers = new List<Timer>();

    [Command("new")]
    public async Task NewTimer(string content, [Remainder] int delay)
    {
        Timer timer = new Timer(content, delay, Context.Channel);
        
        _timers.Add(timer);
        Console.WriteLine(_timers.Count());
        await ReplyAsync("created new timer with id: "   timer.Uuid);
    }

    [Command("list")]
    public async Task ListTimer()
    {
        string reply;

        string reply = string.Join<string>(", ", _timers.Select(x => x.Uuid));
        await ReplyAsync(reply);
    }
}

CodePudding user response:

At times like these, what I try to do is create a minimum reproducible sample that removes anything unrelated to the problem. You could use a quick console app like I did here or a Unit Test. What this seems to show is that your code works as far as is shown:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;

namespace timer_list
{
    class Program
    {
        static void Main(string[] args)
        {
            runAsync();
            Console.ReadKey();
        }
        static async void runAsync()
        {
            var timerHandler = new TimerHandler();
            for (int i = 0; i < 5; i  )
            {
                await timerHandler.NewTimer("unused");
            }
        }
        public class TimerHandler // : ModuleBase<SocketCommandContext>
        {
            private List<Timer> _timers = new List<Timer>();
            public async Task NewTimer(string content)
            {
                Timer timer = new Timer();
                _timers.Add(timer);
                Console.WriteLine(_timers.Count());
                await Task.Delay(1);
            }
            public async Task ListTimer()
            {
                await Task.Delay(10);
            }
        }
    }
}

enter image description here

This makes me wonder if you're making a new instance of TimerHandler every time you use it. If this is the case, try changing:

private List<Timer> _timers = new List<Timer>()

to

private static List<Timer> _timers = new List<Timer>()

and see if that helps!

CodePudding user response:

How do you use the TimerHandler from outside? And also how do you call ListTimer() method from outside as well? I think you have to check the GC points related to TimerHandler class. And new object instantiation of this class.

  • Related