Omission was noticed by @AustinWise. I reproed the failure and this fix for it on linux-x64.
Fixes #81362
if ((th & ComAwareBit) != 0 || comInfo != null)
{
ComAwareWeakReference.SetTarget(ref _taggedHandle, target, comInfo);
+
+ // must keep the instance alive as long as we use the handle.
+ GC.KeepAlive(this);
+
return;
}
#endif
if (th == 0)
return default;
+ T? target;
+
#if FEATURE_COMINTEROP || FEATURE_COMWRAPPERS
if ((th & ComAwareBit) != 0)
- return Unsafe.As<T?>(ComAwareWeakReference.GetTarget(th));
+ {
+ target = Unsafe.As<T?>(ComAwareWeakReference.GetTarget(th));
+
+ // must keep the instance alive as long as we use the handle.
+ GC.KeepAlive(this);
+
+ return target;
+ }
#endif
// unsafe cast is ok as the handle cannot be destroyed and recycled while we keep the instance alive
- T? target = Unsafe.As<T?>(GCHandle.InternalGet(th));
+ target = Unsafe.As<T?>(GCHandle.InternalGet(th));
// must keep the instance alive as long as we use the handle.
GC.KeepAlive(this);
if (th == 0)
return default;
+ object? target;
+
#if FEATURE_COMINTEROP || FEATURE_COMWRAPPERS
if ((th & ComAwareBit) != 0)
- return ComAwareWeakReference.GetTarget(th);
+ {
+ target = ComAwareWeakReference.GetTarget(th);
+
+ // must keep the instance alive as long as we use the handle.
+ GC.KeepAlive(this);
+
+ return target;
+ }
#endif
// unsafe cast is ok as the handle cannot be destroyed and recycled while we keep the instance alive
- object? target = GCHandle.InternalGet(th);
+ target = GCHandle.InternalGet(th);
// must keep the instance alive as long as we use the handle.
GC.KeepAlive(this);
if ((th & ComAwareBit) != 0 || comInfo != null)
{
ComAwareWeakReference.SetTarget(ref _taggedHandle, value, comInfo);
+
+ // must keep the instance alive as long as we use the handle.
+ GC.KeepAlive(this);
+
return;
}
#endif
<!-- Registers global instances of ComWrappers -->
<UnloadabilityIncompatible>true</UnloadabilityIncompatible>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
- <!-- Temporarily disabled due to https://github.com/dotnet/runtime/issues/81362 -->
- <GCStressIncompatible>true</GCStressIncompatible>
</PropertyGroup>
<ItemGroup>
<Compile Include="WeakReferenceTest.cs" />