|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WeakReferenceTestSample
{
public class WeakReferenceUsage
{
WeakReference weakref = null;
private SomeBigClass _somebigobject = null;
public SomeBigClass SomeBigObject
{
get
{
SomeBigClass sbo = null;
if (weakref == null) //When it is first time or object weakref is collected.
{
sbo = new SomeBigClass();
this.weakref = new WeakReference(sbo);
this.OnCallBack("Object created for first time");
}
else if (weakref.Target == null) // when target object is collected
{
sbo = new SomeBigClass();
weakref.Target = sbo;
this.OnCallBack("Object is collected by GC, so new object is created");
}
else // when target object is not collected.
{
sbo = weakref.Target as SomeBigClass;
this.OnCallBack("Object is not yet collected, so reusing the old object");
}
this._somebigobject = sbo; //gets you a strong reference
return this._somebigobject;
}
set
{
this._somebigobject = null;
}
}
# region GarbageEvent
public event Action<string> CallBack;
public void OnCallBack(string info)
{
if (this.CallBack != null)
this.CallBack(info);
}
# endregion
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Did you like his post?
Oh, lets go a bit further to know him better.
Visit his Website :
www.abhisheksur.com to know more about Abhishek.
Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.
http://bit.ly/EXPERTCookBook
Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.
Working as a VP product of
APPSeCONNECT, an integration platform of future, he does all sort of innovation around the product.
Have any problem? Write to him in his
Forum.
You can also mail him directly to
abhi2434@yahoo.com
Want a Coder like him for your project?
Drop him a mail to
contact@abhisheksur.com
Visit His Blog
Dotnet Tricks and Tips
Dont forget to vote or share your comments about his Writing