Since a weak link can be declared by the garbage collector at any time, is there any practical reason to use it?
Of course, there are practical reasons for using it. It would be oddly strange if the framework designers faced the enormous cost of creating a weak frame of reference that would be impractical, don't you think?
I think the question you intended to ask was:
What are realistic situations where people use weak links?
There's a lot. Common is the achievement of a performance goal. Tuning application performance often requires a trade-off between high memory usage and high time usage. Suppose, for example, that there is a complex calculation that you must perform many times, but the calculation is "clean" - the answer depends only on the arguments, and not on the exogenous state. You can create a cache map from the arguments to the result, but then it uses memory. You may never ask the question again, and this memory will be wasted.
Weak links may solve this problem; the cache can become quite large, and therefore time is saved if the same question is asked many times. But if the cache gets large enough for the garbage collector to free up space, it can do it safely.
The disadvantage, of course, is that the garbage collector's cleaning policy is configured to achieve the goals of the entire system, rather than a specific cache problem. If the GC policy and the required cache policy are fairly aligned, then weak links are a very pragmatic solution to this problem.
Eric Lippert Jan 09 '12 at 17:06 2012-01-09 17:06
source share