WeakReference BUG

  • Thread starter Thread starter Wil
  • Start date Start date
W

Wil

I am running on .NET Compact Framework SP2, whenever I call IsAlive()
on
a weak reference, it always throw ArgumentException in the WinCE.NET
4.1
emulator, how do I report this bug? MSDN docs says that this method
is supported by .NET Compact Framework.

WeakReference wr = new WeakReference(obj);
if (wr.IsAlive()) <==== throws ArgumentException!!
....


Wil
 
Wil:

I was unable to compile the code you used so I'm assuming it was pseudocode.
IsAlive is a property not a method so the parens need removed . Anyway,
I've compiled it on the full framework, Smart Device PPC and CE emulator,
as well as deployed it and I can't reproduce it. I'm not implying it's not
really a problem but I'm just wondering if it could possibly be something
else. I used the same code below (with the parens omitted) with the
following code right before it and it's the only thing that I could do to
create an ArgumentException (I could create a InvalidOperationException) by
trying it after it's finalized:

Form1 obj= new Form1();
obj=null;
---your code here

Will the same code targeted to another environment run?
 
Here is the actual code to reproduce the problem in
..NET Compact Framework, I missed the wr.Target = null from the first post.


WeakReference wr = new WeakReference(obj);
wr.Target = null;
if (wr.IsAlive) <==== throws ArgumentException!!
....

By the way the following works fine in the full framework.


Wil
 
This is a known issue and it has been fixed in CF V2.

The problem is: you can not set Target to null; it will cause a problem in
GC later on:

WeakReference wr = new WeakReference(null); << Will cause GC failure
wr.Target = null; << Will cause GC failure

Workaround: if you intended to get rid if the object manually by setting
its reference to null, do not use WeakReference:

object target = new Object();
...
target = null;

if (target != null ) {
/* Alive */
}

If you're using WeakReference, do not set Target to null, let GC collect
object for you:

WeakReference wr = new WeakReference(obj);

// Don't. Let GC collect the object. wr.Target = null;

if (wr.IsAlive) {
/* Alive */
}

Best regards,

Ilya

This posting is provided "AS IS" with no warranties, and confers no rights.
--------------------
 
Back
Top