This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Weak references
I understand the concept of a weak reference, but I am unable to find where I should use a weak reference in C#.
A good example of where to use a WeakReference would be when implementing the EventAggregator pattern.
Say you have the code
eventAggregator.Subscribe<AnEventType>(this.DoSomethingDelegate);
then you will specifically ahve to unsubscribe later if you don't want to have a potential memory leak. See Explicitly Removing Event Handlers for more info.
If however the internals of the EventAggregator hold on to the DoSomethingDelegate using a weak reference, then no unsubscription is necessary.
For further learning, I suggest taking a look at the implementation of EventAggregator in the Microsoft Practices library using ILSpy. This internally uses a WeakReferenceDelegate type which wraps a Weakdelegate and allows subscription without explicit unsubscription and no chance of a memory leak.
Best regards,
Related
This question already has answers here:
Is there an event for when garbage collection occurs in .NET?
(5 answers)
Closed 7 years ago.
I was just wondering if there is an overridable callback for the garbage collector begin/end in the .NET runtime/C#. I will also state that I have no intentions of attempting to control the GC, I am just curious.
And if not, what would be the best way to replicate this behavior?
You can't get notification directly in manged code because managed code is suspended (or at least not guaranteed to run your thread in case of background GC) during GC.
Options:
You can get approximate notification with GC.RegisterForFullGCNotification as shown in
Garbage Collection Notifications article.
You can watch performance counters related to GC if you need approximate time.
You can also capture ETW events to analyze behavior off-line - Garbage Collection ETW Events. There are many links on how to do that - Windows Performance Toolkit and SO questions like Consuming "Event Tracing for Windows" events.
If really necessary you can host CLR yourself and than you'll get notifications about GC - see CLR Indie Out:Hosting CLR and CLR Hosting - part 3. The ultimate method you want when hosting CLR to capture start/end of GC - IHostGCManager::SuspensionStarting.
This question already has answers here:
Why is lock(this) {...} bad?
(18 answers)
Closed 9 years ago.
There are many posts, votes and answers indicating using lock (this) is not a recommends pattern (not to mention a bad one).
Have a look at this one, for example.
As I'm trying to investigate this pattern a little bit, and wanted to ask whether anyone someone can think of a scenario in which using lock (this) is actually recommended, or even a must?
Locking on THIS is evil. This means that someone may decide to lock on your instance. This means that your instance will wait until someone else releases it.
Rule of thumb: never lock on this but create a seperate (private) object to lock.
But... The problem is deeper: locking has a purpose, by locking you provide protection on the upper object(s) but it doesn't prevent updating the underlying objects in for instance a collection.
In most cases a lock isn't a need. Read up on the subject is what I suggest.
Multiple questions on SO cover you question. Shouldn't be hard to build an opinion about the motivation to not lock on this.
An example and pointers for further reading can be found on the blog of Phil Haack
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Proper use of the IDisposable interface
When is Dispose necessary?
If I write a class, which uses graphics, or threads for example, must I implement the IDisposable interface to write a Dispose() method or else memory leak occurs?
Does Dipose() run when the GC reaches it?
If I implement a Dispose() method, shall I call Dispose() on all the disposable fields in the class when "disposing" parameter is true, or is it automatic?
What is "unmanaged resource"?
So I'm pretty unsure about it, I'd appreciate anything that helps me understand these things :)
Thank You
IDisposable is just a pattern to follow. It doesn't do anything, in and of itself, special (other than fitting the requirements of the using statement).
If you're working with a native resource, the resource isn't "known" to the garbage collector. IDisposable is the convention used to allow you to free this resource deterministically.
For details, I wrote a detailed series on IDisposable which talks about why and how to implement it for various scenarios (including wrapping a native resource, encapsulating other IDispsable types, etc).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Are there any guidelines on when you should use a delegate for indirect association, and an observer?
In C#, you get to use delegates for simple call-backs. I guess pointers to function and pointers to member functions can be considered as delegates too (am I right?).
I realize that do use an observer, you need to create an interface, and implement it, so it is more strongly-typed and the relationship is more formal. For a delegate, as long as the function signature and accessibility matches, you can "hook them up".
Does delegates make the observer pattern moot? How do you decide on a delegate vs. an observer pattern?
The observer pattern is already implemented for you in the form of events.
The advantage of events is that they can have multiple subscribers, while with a delegate, you can only have one. Events are better for public interfaces, and scenarios where you don't have complete control over who wants to get notified that something happens. In reality, events are just automatically managed lists of delegates. You'll have to see what makes more sense in your scenario.
Edit: As commenter Rabbi mentions, the above isn't entirely true, as any delegate can become a multicast delegate. The purpose of the event modifier is to make a delegate that can only be invoked inside the class that defines it. This is most useful for ensuring encapsulation in public interfaces.
One advantage of the observer pattern is that if you have a large number of events that are generally always subscribed to by an interested party, then passing a single object into a method to subscribe to the events is much easier than subscribing to each event individually. With C#'s lack of specifying interfaces and methods for anonymous classes as can be done with Java, implementing the observer pattern becomes a bit more laborious so most opt for using events anyway.
Another benefit of the traditional observer pattern is that it handles better in cases where you need to interrogate the subscriber for some reason. I've come across this need with objects that pass a web-service boundary where there are problems with delegates whereas the observer pattern is just simply a reference to another object so it works fine as long as your serialization keeps integrity of references within the object graph like the NetDataContractSerializer does. In these cases it's possible to discriminate between subscribers that should be removed before making the service boundary based on whether the referenced subscriber is also within the same object graph.
Delegates can be used to implement the observer pattern - think of events.
To do it without events take a look here: http://www.dofactory.com/Patterns/PatternObserver.aspx
It wouldn't take much to refactor that into using delegates if you preferred.
The only advantage I can think of with implementing an interface is member name consistency across all implementations.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to share objects across processes in .Net?
I can do this for a single process (single .exe) but how can I do it between processes?
You can do this via remoting. You class needs to inherit from MarshalByRefObject, which will give your clients a proxy to the real object.
You'd need to use some sort of distributed hash table or caching mechanism.
Try to avoid things like remoting if you can, because calls to a remote object can get expensive and start to really hurt performance. If you do go with .net remoting, then carefully consider the interface of the remote object. You should be passing coarse grained data across the process boundry, so avoid chatty interfaces with lots of calls with little bits of data.
What are the requirements of the class that you want to act as a singleton? There might be a totally different way of looking at it. Currently the thinking is that singletons are undesirable because they are difficult to unit test reliably, so avoiding the singleton concept could be the direction to take.
using .Net remoting
(see answers above or by this url: http://msdn.microsoft.com/en-us/library/kwdt6w2k%28VS.71%29.aspx)