I'm writing a small MemoryManager for my WPF application and reached the following problem.
What i do: I store a lot of instances as a WeakReference
in a IList<WeakReference>
. Later, when i want to free all memory, i want to destroy all alive objects in the list.
To do this, i try to get the reference to the object, like this:
foreach (WeakReference wr in references)
{
if (wr.IsAlive == true)
{
if(wr.Target != null)
{
TypedReference tf = __makeref(wr.Target);
}
}
}
But i dont't know how to destroy tf. I tried to use __refval
, but it does not work for me.
Sample:
InstanceDestructManager idm = new InstanceDestructManager();
IList<string> test = new List<string>();
test.Add("123");
idm.AddNullable<IList<string>>(ref test);
idm.Dispose();
// Should not be possible, because after idm.Dispose "test" should be null
test.Add("456");
General code for:
public static void Test(ref object pa)
{
pa = null;
}
Maybe some one has an idea, thank you!
Setting the
WeakReference.Target
tonull
will release the reference to it. There is no such thing as destroy memory in C#. The GC collect memory when there are no references to it. And even then it decides on its own when to free them. GC.Collect forces this. But this is not for production purposes unless you know what you're doing.