Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

111 lines
2.2 KiB
Plaintext

== Why is this an issue?
Usually ``++IntPtr++`` and ``++UIntPtr++`` fields are used to store pointers to unmanaged resources and the finalizer will free the unmanaged resource pointed to by the pointer fields. If the garbage collector finalises the object while the managed resources are still in use it could lead to serious, hard to diagnose bug. To prevent this from happening the object should be kept alive by calling ``++GC.KeepAlive(this)++`` in methods calling unmanaged code on this pointers.
=== Noncompliant code example
[source,csharp]
----
using System;
namespace MyLibrary
{
class Foo
{
private IntPtr res;
Foo()
{
GetRes (res);
}
~Foo()
{
FreeRes (res);
}
void Bar() // Noncompliant
{
UseRes(res);
}
// Methods that would typically make calls to unmanaged code.
void GetRes(IntPtr p)
{
// Allocate the resource ...
}
void FreeRes(IntPtr p)
{
// Free the resource and set the pointer to null ...
}
void UseRes(IntPtr p)
{
// Use the resource in unmanaged code ...
}
}
}
----
=== Compliant solution
[source,csharp]
----
using System;
namespace MyLibrary
{
class Foo
{
private IntPtr res;
Foo()
{
GetRes (res);
}
~Foo()
{
FreeRes (res);
}
void Bar()
{
UseRes(res);
GC.KeepAlive(this);
}
// Methods that would typically make calls to unmanaged code.
void GetRes(IntPtr p)
{
// Allocate the resource ...
}
void FreeRes(IntPtr p)
{
// Free the resource and set the pointer to null ...
}
void UseRes(IntPtr p)
{
// Use the resource in unmanaged code ...
}
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)
=== on 28 Jan 2019, 14:34:46 Amaury Levé wrote:
We cannot find how to get the original FxCop to report any issue + the description is not precise enough so we cannot find what/how the rule should be implemented.
cc [~nicolas.harraudeau]
endif::env-github,rspecator-view[]