rspec/rules/S4213/csharp/rule.adoc
2021-06-08 14:23:48 +02:00

101 lines
1.9 KiB
Plaintext

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
----
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
----
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)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]