Hello, I'm trying to understand a situation but until then I could not solve it. Imagine that we have a class X that has a timer that is started by the constructor. Now imagine that this same class is instantiated inside a thread.
By doing some tests in my code, I realized that if I have a dispose in the thread, the timer that is running in the class will continue to run. I already tried to create a list and try to stop the timer of the objects but it still did not 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();
}
}
}