Sheen Space

Posts Tagged ‘.NET

Question about .NET GC

leave a comment »

A question at StackOverflow site:

I have had similar question about GC and raised it in this thread:

quoted below:

Here is another great article about GC may occur at unexpected point of code execution:

Lifetime, GC.KeepAlive, handle recycling – by cbrumme

My question is how can I reproduce forced GC at the point mentioned in the article? I tried to put GC.Collect() at beginning of OperateOnHandle(), and defined destructor for class C but seems not working. Destructor is invoked always at end of program.

After others’ help now I can reproduce this behavior. Refer to the question I raised above for update and code I put there. The article written by cbrumme is based on .NET 1.0 and Microsoft has provided elegant solution from .NET 2.0 onwards, that is SafeHandle. Excuse my ignorance.

Written by Ying

19/09/2010 at 11:31

C# Notes: Class Layout – explicitlayout

leave a comment »

Description in CLI specification:

explicitlayout: A class marked explicitlayout causes the loader to ignore field sequence and to use the explicit layout rules provided, in the form of field offsets and/or overall class size or alignment.

This is usually used to define exact class bit layout, to communicate with unmanaged code, like C/C++ code, which requires accurate class layout and / or alignment; or to send over network, in specific packet format, like TCP/IP.


[StructLayout(LayoutKind.Explicit, Size=16, CharSet=CharSet.Ansi)]
public class MySystemTime
    [FieldOffset(0)]public ushort wYear;
    [FieldOffset(2)]public ushort wMonth;
    [FieldOffset(4)]public ushort wDayOfWeek;
    [FieldOffset(6)]public ushort wDay;
    [FieldOffset(8)]public ushort wHour;
    [FieldOffset(10)]public ushort wMinute;
    [FieldOffset(12)]public ushort wSecond;
    [FieldOffset(14)]public ushort wMilliseconds;

Note that, when FieldOffset is used, it takes precedence over Pack and Size specified in StructLayout attribute.

Written by Ying

19/09/2010 at 01:24

Posted in Programming, Technology

Tagged with ,