Weak References

Weak References

In computer programming, a weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference. An object referenced only by weak references – meaning "every chain of references that reaches the object includes at least one weak reference as a link" – is considered weakly reachable, and can be treated as unreachable and so may be collected at any time. Most objects that are referenced must be kept in memory until they are unreachable. But with WeakReference, objects that are referenced can be collected.

WeakReference Class in .NET represents a typed weak reference, which references an object while still allowing that object to be reclaimed by garbage collection. A weak reference enables the garbage collector to collect an object while still allowing an application to access the object. If you need the object, you can obtain a strong reference to it and prevent it from being collected. WeakReferences are supported in .NET framework 4.5. Any public static (Shared in Visual Basic) members of WeakReferences are thread safe. Any instance members are not guaranteed to be thread safe.

The WeakReference class can be very useful but, when used incorrectly, it makes it easy to introduce intermittent bugs into your software. These relate to the incorrect use of the Target property, which holds the wrapped object, and the IsAlive property, which can be used to find out if the reference has been garbage collected.

Version 4.5 of the .NET framework introduces a new class for holding weak references that reduces the risk of introducing defects. It is a generic class, so removes the use of casting required by WeakReference. The class is named, WeakReference.

Weak References
added 5 years 1 month ago

- Open a text file and read line by line in C#
- Convert.ToInt32() vs Int32.Parse() in C#
- How to C# Linq Group By by paramater/field names
- Simple Injector
- How to check memory consumption in c#
- How can I implement C/C++ "union" in C#?
- How to Open and Read From Excel File in C#
- Weak References
- Lazy Initialization
- Enable Nuget Package Restore
- OnixS FIX Engine
- Rapid Addition FIX API
- How to change DateTime format in C#
- How to change number decimal seperator in C#?