Posts Tagged ‘developers’

Comments (1)A detector for memory leaks on Silverlight applications

Added by mike | February 11th, 2009> | 19:02
Categories:   code   for developers   silverlight

Abstract: Currently there’s no memory profiler for Silverlight

If you’ve ever programmed in Silverlight, you’ve probably wondered whether your objects in memory were collected by the GC (garbage collector) or not. What if the objects you create stay in the memory for the whole life-time of your application – will you know?
Regular .NET memory profilers don’t work with Silverlight applications and therefore, if we have a memory problem and want to examine it, the only way to approach the problem is to convert our project to a WPF application, which is difficult in the best of cases, and in my scenario was nearly impossible.

When should you use a memory leak detector?

The memory leak detector I wrote is meant for use in those cases where you have the feeling one of the objects you wrote isn’t being collected when it should be by the GC. You can use the memory leak detector to monitor this behavior.

How to use the Silverlight application memory leaks detector?

To use my memory leak detector first add the object you want to monitor by calling the detector’s ‘AddReference’ method in the object’s constructor. Next, at a point where the object should have been already collected by the GC call the ‘Check’ method to verify that it was indeed collected and is no longer in memory.

How is the GC duped into collecting objects despite the fact that the memory leak detector has references to them?

The trick behind this memory leak detector is the usage of the ‘WeakReference’ class. ‘WeakReference’ is a class that provides the ability to reference an existing object in memory, without preventing the object from being collected by the GC. For more information about the ‘WeakReference’ class visit: http://msdn.microsoft.com/en-us/library/system.weakreference.aspx

The Code – an overview

The memory leak detector manages a main list named ‘elementsList’ consisting of ‘ObjectStruct’ elements. Each element contains a ‘WeakReference’ to the monitored object and a few other debug values. You can use the ‘StackTrace()’ in order to identify the monitored object’s creator. This field can help finding the source of the memory leak. The code is divided into three main static public methods. The first two must be called while the last one, ‘SignalDisposed’, is for further debugging.

Main Methods:

  • AddReference’ – Adds the object you want to monitor to the memory detector. You can choose whether you want to create the ‘StackTrace’ upon creating the object or not. The object’s constructor is a good place to call this method.
        [Conditional("DEBUG")]
        public static void AddReference(object obj)
        {
            lock (lockObject)
            {
                // avoiding dups - can happen when adding an element
and its base-class to the profiler
                if (elementsList.Any(p => p.Reference.IsAlive &&
p.Reference.Target == obj))
                    return;
                elementsList.Add(new ObjectStruct(new WeakReference(obj),
generationCounter, new StackTrace().ToString()));
                //elementsList.Add(new ObjectStruct(new WeakReference(obj),
generationCounter, null));
            }
        }

    -

  • Check’ – Use this method to check the memory condition. A good place for implementing this call would be an idle state of your application, where most of the objects already created can be disposed and collected. Each call to the ‘Check’ method increases the static generation counter by 1 providing us a method for following when the monitored objects where instantiated. The ‘Debugger.Break()’ command stops the application at a point allowing you to examine all objects alive in memory.
        [Conditional("DEBUG")]
        public static void Check()
        {
            lock (lockObject)
            {
                long memUsage = GC.GetTotalMemory(true);
                for (int i = 0; i < elementsList.Count; i++)
                    if (!elementsList[i].Reference.IsAlive)
                        elementsList.RemoveAt(i--);
            }
            generationCounter++;
            Debugger.Break();
        }

    -

  • SignalDisposed’ – My experience hunting for memory leaks with this detector during my work on our semantic web Firefox add-on, led me to the conclusion that there is value in having a Boolean variable indicating whether or not the dispose method of the monitored objects was called. To debug your leak, call this method within the ‘Dispose()’ method to detect scenarios where the ‘Dispose()’ method was called but the object remains in memory.
        public static void SignalDisposed(object obj)
        {
            lock (lockObject)
            {
                var objectsToSignal = elementsList.Where(p =>
p.Reference.IsAlive && p.Reference.Target.Equals(obj));
                if (objectsToSignal.Any() && objectsToSignal.Count() == 1)
                {
                    var objectToSignal = objectsToSignal.First();
                    objectToSignal.DisposedSignaled = true;
                }
            }
        }

-

Notes:

  1. All three functions have the ‘Conditional(“DEBUG”)’ attribute that allows using the memory leak detector freely in a project without worrying about performance in the release version of the application. For more information about the ‘Conditional’ attribute visit: http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx
  2. The class supports multi-threading.

Ideas for future development:

Knowing which object holds a reference to the in memory monitored objects would be great…

This post was written by Amit Kanfer.

Comments (6)How to determine if a computer is running multiple CPUs in a Silverlight, RIA or web page situation

Added by mike | February 9th, 2009> | 13:02
Categories:   code   for developers

Abstract – How can you tell if the computer you’re running on has more than one CPU?

Now that most new computes have multiple processors we are seeing a rapid rise in the usage of parallel programming. Many libraries supply efficient code for computers with multiple cores, but how can you tell if the computer you are running on indeed has more than one CPU?

Why is the need to identify multiple CPUs becoming a pressing issue now?

Most programs today are multithreaded. More and more libraries are written for effective multithreaded code, with the assumption that this code will be run on computers with multiple cores. The need to know whether the computer is multi-core is imperative yet in certain cases, like RIAs and web applications, you can’t simply “ask” the operating system outright how many cores it is using.

How are multiple CPUs identified “normally”?

When running in the .NET environment you can easily get the exact number of processors by using the following code:

System.Environment.ProcessorCount;

The bad news is that this property isn’t available for situations where you don’t have permission to ask the operating system about the number of processors the system is running. This is exactly the situation you are in when you are developing web pages and RIAs based on MS Silverlight or Adobe Flash.

How can multiple CPUs be identified in a Silverlight application, or similar RIA situation?

I wrote the following code for determining whether a computer has multiple cores using only the basic operations available in any language and on any platform. The code runs two threads in tandem and checks if they can really run simultaneously.

SpinWait – The magic key

Roughly defined a thread’s ‘Quanta’ is the minimum time that the operating system will dedicate to a thread without making a context switch. A quanta is usually somewhere between 10 and 15 milliseconds long. The code I wrote keeps the processors busy for the amount of instructions given (like creating an empty loop with an increased index), however unlike ‘Sleep’ this code prevents context switching from the thread unless it spins in excess of the thread’s quanta.

Here is the code I used:

public static bool MoreThanOneCPU()
        {
         // will indicate that the computer has more than one processor
         bool moreThanOne = false;
         // will close the other thread eventually
         bool toContinue = true;
         ManualResetEvent m = new ManualResetEvent(false);
         // open the secondary thread
         Thread t = new Thread(new ThreadStart(delegate
         {
             // make sure it has time to start
             m.Set();
             // set the flag while not signaled to stop
             while (toContinue)
                 moreThanOne = true;
         }));
         t.IsBackground = false;
         t.Start();
         // waiting for the thread to start
         m.WaitOne();
         // forcing context switch
         Thread.Sleep(0);
         // begining of the threads quanta
         moreThanOne = false;
         // spin long enough for the other thread to set the flag
         // but still shorter than the quanta
         Thread.SpinWait(100000);
         // stop the secondary thread
         toContinue = false;
         // return the result
         return moreThanOne;
}

Note: The method described here isn’t deterministic as the OS could demand a context switch due to a system interrupt, or for some other reasons, in which case the code might report erroneously that the computer has more than one core.

What the code does

The code opens a thread dedicated to repeatedly setting a boolean flag, with the idea of having this thread run on a secondary core, if one exists. In order to ensure that the thread has started and is ready to loop a ‘wait’ handle is used. The main thread waits for the secondary thread to start and then calls ‘Thread.Sleep(0)’ to force the context switch. This ensures the next instruction will execute at the beginning of the threads’ quanta. In order to allow the other thread to set the flag on the other core while we are still spinning we ‘SpinWait’ 100000 instructions. Since the ‘SpinWait’ is shorter than the thread’s quanta it won’t force a context switch. Now we can examine our outcome: If the flag has been set during the elapsed time we know it must have been set by another processor that processed the thread while the other process was busy spinning.

Implementation and usage:

I developed the code presented above while I was researching the performance of Headup, our Semantic Web Silverlight application. I discovered we were wasting a lot of time on mandatory locks that, although required, didn’t justify the accrued overhead.

Spinlock – good value, low cost

After some research I decided to boost our application’s performance by using the ‘SpinLock’ implementation, which utilizes the computer’s two cores to make an efficient lock. I was pleasantly surprised to discover the implementati0n required very little effort.

SpinLock’s secret is that instead of using a system call, like ‘lock’ does, it uses ‘SpinWait()’ to let the other core release the lock. Of course if the computer hasn’t got another core, this is useless. In order to know whether I could use ‘SpinLock’ effectively I first needed to validate that the machine I was running had more than one processor. Hence the code above…

Examples and Notes:

Ideas for the future:

  • Because of the risk of false positives it’s advisable to run the method several times and use the most frequent outcome. This will certainly improve results.
  • By using multiple threads it should be possible to discover the exact amount of processors and not merely whether the machine has one or more.

Thanks go to Yogi for writing this post.