Question about CommandBehaviorBase<T>

Topics: Prism v4 - WPF 4
Jul 21, 2011 at 2:28 AM

While looking at the implementation of this base class, I noticed that in the UpdateEnabledState method, a strong reference is not created before using TargetObject.  I thought the correct use of weak reference was to first make a strong reference, then check if that reference == null?  I'm probably missing something here, but isn't it possible that TargetObject could be collected between the if statement and where its used in the else statement, as extremely unlikely as that may be?

Jul 22, 2011 at 2:38 PM


The use of a weak reference is to prevent an object to be kept in memory by that reference (that is to say, the object will remain in memory if it has at least one strong reference anywhere else). If you make a strong reference first, the purpose of the weak reference will be broken, as the target object would be kept in memory unnecessarily, only being referenced by the Command Behavior.

As for the possibility you're mentioning, based on my understanding of the working of garbage collection in .NET, it seems that the risk for that to happen shouldn't account for the cost of using a strong reference (since the object is being used in the same block of code, which flows synchronously).

I hope you find this helpful.

Guido Leandro Maliandi