I am pretty sure this has been discussed somewhere already on the net, but it was hard to find the answer and testing it myself was faster so here it is.
The answer is: YES, it would still correctly unsubscribe from the event.
If you run it, you will see only one line in the console output.
To demonstrate a leak, remove using() statement. You should see a second console output, indicative of an instance o Driver still hanging around in memory.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EventTest
{
class Program
{
static void Main(string[] args)
{
Car c = new Car();
using (Driver d = new Driver(c))
{
d.DoWork();
}
GC.Collect();
GC.WaitForPendingFinalizers();
c.Start();
}
}
public class Driver : IDisposable
{
Car _car;
public Driver(Car car)
{
_car = car;
//_car.Started += new EventHandler(car_Started);
_car.Started += car_Started;
}
public void DoWork()
{
_car.Start();
}
void car_Started(object sender, EventArgs e)
{
Console.WriteLine("Car has started");
}
public void Dispose()
{
//_car.Started -= new EventHandler(car_Started);
_car.Started -= car_Started;
}
}
public class Car
{
public event EventHandler Started;
public void Start()
{
if (Started != null)
{
Started(this, EventArgs.Empty);
}
}
}
}
0 件のコメント:
コメントを投稿