Not so safe TorqueSafePtr
by AIDan · in Torque X 3D · 06/02/2009 (2:42 pm) · 2 replies
The problem is that the object is cleared. This can cause problems when using different threads.
For example:
if(handle.Initialized)
handle.Object.DoSomething();
The handle could become invalid after checking the Initialized property.
As the object is cleared, handle.Object will return null.
The following would be much safer:
The advantage is that even after the object became invalid, Object still returns a valid object so the currently running process can continue. When it is done or the next time it checks IsValid, the process can bail out.
For example:
if(handle.Initialized)
handle.Object.DoSomething();
The handle could become invalid after checking the Initialized property.
As the object is cleared, handle.Object will return null.
The following would be much safer:
public sealed class Handle<T>
{
protected bool _isValid;
protected T _object;
public bool IsValid
{
get { return _isValid; }
set
{
// we can only invalidate handles
if(!value)
_isValid= false;
}
}
public T Object
{
get { return _object; }
}
public Handle(T obj)
{
_object= obj;
_isValid= obj !=null;
}
}The advantage is that even after the object became invalid, Object still returns a valid object so the currently running process can continue. When it is done or the next time it checks IsValid, the process can bail out.
About the author
#2
Is not thread safe, no matter how you slice it.
It should be more like:
I think you're missing the point of Handle<>.
06/02/2009 (4:59 pm)
The problem is that this:if(handle.Initialized) handle.Object.DoSomething();
Is not thread safe, no matter how you slice it.
It should be more like:
MyObject x = handle.Object;
if (x != null)
{
x.doSomething();
}
else
{
// Handle the case where the object is no longer valid
}I think you're missing the point of Handle<>.
Torque Owner Trent