How dispose System.Threading.Timer correctly?
I have got this result:
pub_MyEvent1
pub_MyEvent1
pub_MyEvent1
pub_MyEvent1
new pub_MyEvent
pub_MyEvent1
new pub_MyEvent
Code:
class Program
{
static void Main(string[] args)
{
Publisher pub = new Publisher();
pub.MyEvent += new EventHandler(pub_MyEvent1);
Console.ReadLine();
pub = new Publisher();
pub.MyEvent += new EventHandler(pub_MyEvent);
Console.ReadLine();
}
static void pub_MyEvent(object sender, EventArgs e)
{
Console.WriteLine("new pub_MyEvent");
}
static void pub_MyEvent1(object sender, EventArgs e)
{
Console.WriteLine("pub_MyEvent1");
}
}
public class Publisher : IDisposable
{
private System.Threading.Timer _timer;
private EventHandler _myEvent;
public event EventHandler MyEvent
{
add { _myEvent += value; }
remove { _myEvent -= value; }
}
protected void OnMyEvent(Object state)
{
if (_myEvent != null)
{
foreach (EventHandler handler in _myEvent.GetInvocationList())
{
handler(this, new EventArgs());
}
}
}
public Publisher()
{
_timer = new System.Threading.Timer(new System.Threading.TimerCallback(OnMyEvent), null, 1000, 1000);
}
public void Dispose()
{
if (_timer != null)
_timer.Dispose();
}
}