0
Hello, I’m trying to understand a situation but so far I haven’t been able to solve it. Imagine that we have an X class that has a timer that is started by the constructor. Now imagine that this same class is instantiated inside a thread.
Doing some tests on my code I realized that if I give Ispose in the thread, the timer running in the class will continue running. I tried to create a list and try to stop the timer of the objects but it still didn’t work.
An example of the problem in a c console solution# -
public class Phone
{
private static System.Timers.Timer aTimer;
private int ID;
public Phone(int ID)
{
this.ID = ID;
}
public void Start()
{
aTimer = new System.Timers.Timer(2000);
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
public void Stop()
{
aTimer.Stop();
aTimer.Dispose();
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("Radio ID : " + ID);
Console.Write(" Launch thread: {0}", Thread.CurrentThread.ManagedThreadId);
}
}
class Program
{
static void Main()
{
List<Task> list = new List<Task>();
for (int i = 0; i < 10; i++)
{
Phone A = new Phone(i);
list.Add(Task.Factory.StartNew(() => {
A.Start();
}));
}
Console.ReadKey();
Console.WriteLine(" STOPPING THREAD");
for (int i = 0; i < 10; i++)
{
list[i].Dispose();
}
Console.ReadKey();
}
}
}