Sheen Space

Posts Tagged ‘.NET

Question about .NET GC

leave a comment »

A question at StackOverflow site: http://stackoverflow.com/questions/1716353/object-finalize-override-and-gc-collect

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

http://stackoverflow.com/q/3745507/451875

quoted below:

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

Lifetime, GC.KeepAlive, handle recycling – by cbrumme http://blogs.msdn.com/b/cbrumme/archive/2003/04/19/51365.aspx?wa=wsignin1.0

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.

Advertisements

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.

Usage:

[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 ,