There is some sample code:
public class Publisher
event Published()
end class
public class Subscriber
public sub new(Publisher as Publisher)
addhandler Publisher.Published,
sub()
end sub
end sub
end class
Does registering to the Publisher event in Subscriber constructor prevent Subscriber from being garbage collected even if an empty lambda function, that doesn't capture Subscriber, is passed as event handler?
Is it the same in C#?
Edit
A simple console application to test it:
Sub Main()
Dim Publisher As New Publisher
For i = 1 To 1000000
Dim Subscriber As New Subscriber(Publisher)
Next
GC.Collect()
Dim TotalMemory = GC.GetTotalMemory(True)
Trace.WriteLine(TotalMemory)
End Sub
Unfortunately, the application consumes 36 megabytes of memory after garbage collection, which means that all Subscribers stay in memory!
Debug and Release on different target frameworks 2.0, 3.0, 3.5, 4.0, 4.5 give the same results.
If you don't reference anything related to Subscriber in your anonymous function, it will be compiled as static method of Subscriber class and as such it won't prevent any instances of Subscriber class to be garbage collected. You may want to look at this link - http://blogs.msdn.com/b/oldnewthing/archive/2006/08/02/686456.aspx - for more info.
UPDATED. Code below shows almost the same values of total memory, when running in Release mode (in Debug mode it indeed works as you said):
internal class Program {
private static void Main(string[] args) {
Console.WriteLine("Before: {0}", GC.GetTotalMemory(true));
var pub = new Publisher();
for (int i = 0; i < 1000000; i++) {
var sub = new Subscriber(pub);
}
GC.Collect();
Console.WriteLine("After: {0}", GC.GetTotalMemory(true));
Console.ReadKey();
}
}
public class Publisher {
public EventHandler Published;
}
public class Subscriber {
public Subscriber(Publisher pub) {
pub.Published += delegate { };
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With