Summary: C # /. NET is supposed to collect garbage. C # has a destructor used to clear resources. What happens when object A is a garbage collection of the same row, I try to clone one of its member variables? Apparently, on multiprocessors, sometimes the garbage collector wins ...
Problem
Today, in training in C #, the teacher showed us some code that contained an error only when running on multiprocessors.
I will summarize to say that sometimes the compiler or JIT screws rise, calling the finalizer of a C # class object before returning from its called method.
The full code provided in the Visual C ++ 2005 documentation will be posted as an โanswerโ so as not to ask very big questions, but the main ones are below:
The following class has a hash property that returns a cloned copy of the internal array. At is, the first element of the array has a value of 2. In the destructor, its value is set to zero.
The point is this: if you try to get the "Hash" property in the "Example", you will get a clean copy of the array, whose first element is still 2, because the object is used (and as such, not garbage collection / end):
public class Example
{
private int nValue;
public int N { get { return nValue; } }
private byte[] hashValue;
public byte[] Hash { get { return (byte[])hashValue.Clone(); } }
public Example()
{
nValue = 2;
hashValue = new byte[20];
hashValue[0] = 2;
}
~Example()
{
nValue = 0;
if (hashValue != null)
{
Array.Clear(hashValue, 0, hashValue.Length);
}
}
}
But everything is so simple ... The code using this class is wokring inside the stream and, of course, for the test, the application is highly multithreaded:
public static void Main(string[] args)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
t.Join();
}
private static void ThreadProc()
{
while (running) DoWork();
}
The static DoWork method is the code in which the problem occurs:
private static void DoWork()
{
Example ex = new Example();
byte[] res = ex.Hash;
if (res[0] != 2)
{
}
}
1 000 000 DoWork, -, Garbage Collector "ex", , , "". , , , ( 1- 2).
, , , [1] DoWork, :
byte[] res2 = ex.Hash2;
byte[] res = (byte[])res2.Clone();
, Hash2 - , :
public byte[] Hash2 { get { return (byte[])hashValue; } }
, : , #/. NET, JIT?
.
http://blogs.msdn.com/cbrumme/archive/2003/04/19/51365.aspx
http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx
, . +1...
: -)
2
Linux/Ubuntu/Mono, , ( , ..)