Feeds:
Posts
Comments

Archive for February, 2009

Once in a while you have people complaining in the forums that their .NET applications are not releasing memory but that if they minimize the app and restore it, then the memory usage goes down. Why this happens is explained in this Microsoft KB article :

You can simulate this in your code too (under extreme conditions when you really need the memory). In my case I had to do this in an app that loaded very large PNG files – once in a while we’d get a memory exception and then I’d call this method and retry and it would work. It does sound a bit hack-ish but there was nothing else we could do.

[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize",
  ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
private static extern int SetProcessWorkingSetSize(
  IntPtr process, int minimumWorkingSetSize, int maximumWorkingSetSize);

public static void ReleaseUnusedMemory()
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
    SetProcessWorkingSetSize(
        System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}

I thought it’d be nice to post this here in case anyone else ever needs this.

Read Full Post »

Recently in the MSDN Forums, someone wanted to know how he could use reflection to invoke a constructor that took a ref parameter. Personally I can’t think of any reason why a constructor would have a ref parameter, and try as I did I could not dig up that thread (neither Google nor MSDN forum search returns the right thread in the search results).

Anyway his main issue was that he did not know how to get the type of a ref string argument. C# will not let you do typeof(string&) which is what he wanted. The solution was to use Type.GetType("System.String&"). In case anyone ever has this bizarre requirement, here’s a small sample that shows how this can be done.

class A
{
    public A(){}

    public A(ref string id)
    {
        id = "AAA";
    }
}

class B
{
    public B(){}

    public B(ref string id)
    {
        id = "BBB";
    }
}

class Program
{
    static void Main()
    {
        new Program().Foo();
    }

    private void Foo()
    {
        string s = "SSS";
        Console.WriteLine(s);
        Bar(typeof(A), ref s);
        Console.WriteLine(s);
        Bar(typeof(B), ref s);
        Console.WriteLine(s);
    }

    private void Bar(Type type, ref string s)
    {
        var ctor = type.GetConstructor(
          new Type[] { Type.GetType("System.String&") });
        var arr = new object[] { s };
        ctor.Invoke(arr);
        s = (string)arr[0];
    }
}

Note how I have to copy back the string from the object array. This is because while the string is passed by ref, it’s the reference in the array that’s passed to the constructor – and not the string that was passed as a parameter to the Bar method. The difference may be subtle unless you think about it.

Read Full Post »

I am writing this blog entry as a reminder to myself to be careful when using static fields or properties, and I wanted to document some silliness on my part for posterity. Recently I was working on some code where I wanted to keep track of derived class instances by storing them in a static list in the base class. The classes I was working on were non-trivial and fairly complex (and the original versions were not even authored by me). So for the sake of this blog entry, I’ve come up with simplified base and derived classes to explain what happened. Here’s what the base class looked like :

class Base
{
    private static List list = new List();

    public static List List
    {
        get { return Base.list; }
    }

    private Base()
    {
        Base.list.Add(this);
    }

    public string Name { get; private set; }

    public Base(string name) : this()
    {
        this.Name = name;
    }
}

And here’s what a typical derived class would be like :

class Derived : Base
{
    public static Derived Nish = new Derived("Nish");
    public static Derived Andrew = new Derived("Andrew");
    public static Derived Megan = new Derived("Megan");

    public Derived(string name) : base(name)
    {
    }
}

I thought it was all good, and then ran some code that did an iteration of the list :

foreach (Base item in Derived.List)
{
    Console.WriteLine(item.Name);
}

To my tremendous surprise nothing came up and the list was empty. For a full 10 minutes, the idiot that I am, I kept pondering over this and wondering what the heck was going on. Then it hit me just like that. Even though I was accessing Derived.List, that was just a C# syntactic convenience that allowed me to write it that way because Derived did not have a List member at all (the compiler auto-fixes this to Base.List in the generated MSIL). The property was defined on Base, and thus Derived has not been accessed yet when I iterate Derived.List. So Derived‘s static initialization has not even happened yet. Once I realized my folly, fixing it was straight forward, I had to bring down the List property to the Derived class. This meant that every derived class had to do that which was a bit of an annoyance but not so much as to be a show stopper. Here’s the correct code (for my simplified example) :

class Base
{
    protected static List list = new List();

    private Base()
    {
        Base.list.Add(this);
    }

    public string Name { get; private set; }

    public Base(string name) : this()
    {
        this.Name = name;
    }
}

class Derived : Base
{
    public static Derived Nish = new Derived("Nish");
    public static Derived Andrew = new Derived("Andrew");
    public static Derived Megan = new Derived("Megan");

    public Derived(string name) : base(name)
    {
    }

    public static List List
    {
        get { return Base.list; }
    }
}

Next time you are using static properties in your base classes, just be a little careful – I know I’ll be.

Read Full Post »

Follow

Get every new post delivered to your Inbox.