WeakReference/GC/multithread question

  • Thread starter Thread starter Thibaud Bouquely
  • Start date Start date
T

Thibaud Bouquely

Hello !

I just read source code witch use WeakReference object to implements some
Cache system.

I can read the classic code like this

// point A
if (myWeakReference.IsAlive)
// point B
((MyClass)myWeakReference.Target).DoSomething();
// point C

I am trouble with theses code Lines :
I don't know if it is the main thread to do sometime GC.Collect() or
another thread ?
If it is another Thread, I think we need a critical section between "Point
A" and "Point C"

moreover, It is possible we use this technic with Compact Framework
application. >> do you need to be careful about something else ?

Thanks for your help !
 
Thibaud Bouquely said:
I just read source code witch use WeakReference object to implements some
Cache system.

I can read the classic code like this

// point A
if (myWeakReference.IsAlive)
// point B
((MyClass)myWeakReference.Target).DoSomething();
// point C

I am trouble with theses code Lines :
I don't know if it is the main thread to do sometime GC.Collect() or
another thread ?

More likely is that another thread will cause a garbage collection
implicitly. I'm not entirely sure what your question is here, but any
thread can trigger a garbage collection.
If it is another Thread, I think we need a critical section between "Point
A" and "Point C"

moreover, It is possible we use this technic with Compact Framework
application. >> do you need to be careful about something else ?

I suggest just using WeakReference.Target and testing the result of
nullity after retrieving it. That way you've got the reference before
you do the test, so if it's alive, you don't need to worry about it
then being GC'd.
 
Yes, there is a potential race condition here.

You can easily get around it with:

MyClass myObj = (MyClass)myWeakReference.Target;
if (myObj != null)
myObj.DoSomething();

Bruno
 
Thanks for yours responses

We could say "MyWeakReference.IsAlive" is not very useful, no ?

the only "good" way to know is a target is alive is to use your technic ...
....
return (GCHandle.InternalGet(num1) != null);

and in WeakReference.Get_Target we can read too :
object obj1 = GCHandle.InternalGet(num1);
return obj1;
 
Thibaud Bouquely said:
Thanks for yours responses

We could say "MyWeakReference.IsAlive" is not very useful, no ?

Agreed! I have used weak references a number of times, and I never used this
call.

Bruno.
 
Back
Top