Of all the cur­sors that we come across on a daily basis, the grab image and grab­bing image cur­sors are two notable absen­tees in the list of sup­ported cur­sors in WPF/Silverlight.

So if you hap­pen to need these two cur­sors as I did ear­lier in the day, then here’s a few easy steps to get you going:

1. Down­load the grab.cur and grabbing.cur files from here and here.

2. Include them in your project, under a Resources/Cursors folder, like this:

image

3. Make sure the Build Action for both is set to ‘Resource’ (which is sim­i­lar to Embed­ded Resource, except Resource is intended for WPF/Silverlight and Embed­ded Resource is intended for older technologies):

image

4. You won’t be able to put them in as Resources directly, but you can put a ref­er­ence to them using dummy TextBlock controls:

<UserControl.Resources>
    <ResourceDictionary>
        <TextBlock x:Key="CursorGrab" Cursor="Resources/Cursors/grab.cur"/>
        <TextBlock x:Key="CursorGrabbing" Cursor="Resources/Cursors/grabbing.cur"/>
    </ResourceDictionary>
</UserControl.Resources>

5. Now you can retrieve the ref­er­ences to these cur­sors in code like this:

_grabCursor = ((TextBlock) Resources["CursorGrab"]).Cursor;
_grabbingCursor = ((TextBlock) Resources["CursorGrabbing"]).Cursor;
Share

So often when you are work­ing on a solu­tion with mul­ti­ple projects you will have to change the con­tents of the AssemblyInfo.cs file for each project so the DLLs show the cor­rect com­pany, trade­mark, and most impor­tantly ver­sion num­bers. This is a very labo­ri­ous task and chances are you might have been won­der­ing how you can put the com­mon set­tings in one file whilst leav­ing you free to use the AssemblyInfo.cs file in the project for project-specific settings.

Well, the solu­tion is sim­ple really, you can cre­ate a file, say SharedAssemblyInfo.cs, at the solution’s root direc­tory and put all the com­mon set­tings there. Then, every time you want to make use of the com­mon set­tings, just right-click on your project and Add an Exit­ing Item…, browse to the SharedAssemblyInfo.cs, and make sure you choose to Add As Link.

image

Once you’re done, you will see the SharedAssemblyInfo.cs in your project, along with a short­cut label:

image

Now you can safely remove all the com­mon set­tings from the project’s AssemblyInfo.cs!

Share

As I’ve men­tioned in my pre­vi­ous post, the biggest prob­lem with using the .Net Thread­Pool is that there’s a lim­ited num­ber of threads in the pool and you’ll be shar­ing with other .Net frame­work classes so you need to be on your best behav­iour and not hog the thread pool with long run­ning or block­ing jobs.

But what if you need to do lots of con­cur­rent IO jobs which blocks and want your main thread to wait till all these threads are done? Nor­mally in these cases you will need to cre­ate your own threads, start them and then join all the spawned threads with your main thread.

This approach would of course carry with it the over­head of cre­at­ing and destroy­ing threads, and if you’re doing the same thing in lots of dif­fer­ent places simul­ta­ne­ously it can also push your CPU to 100% too. For exam­ple, you’ve got mul­ti­ple threads run­ning, and each spawns many more threads to do their con­cur­rent IO jobs at the same time.

In sit­u­a­tions like this, you almost want to have a thread pool for these jobs which is sep­a­rate from the .Net Thread­Pool, that way you avoid the over­heads of using your own threads and can curb the CPU usage because you’re not cre­at­ing new threads unnec­es­sar­ily. But to cre­ate your own imple­men­ta­tion that’s any­where near as good as the .Net Thread­Pool is no small under­tak­ing, which is why I was so glad when I found out about Smart­Thread­Pool.

Here are some of the fea­tures which I found really useful:

Smart­Thread­Pool objects are instantiable

Which means you can cre­ate dif­fer­ent thread pools for dif­fer­ent type of jobs, each with an appro­pri­ate num­ber of threads. This way each type of jobs have its own ded­i­cated pool of threads and won’t eat into each other’s quota (and that of the .Net frame­work classes!).

Work items can have a return value, and excep­tions are passed back to the caller

Get­ting return val­ues from thread pool threads has always been a pain, as is catch­ing any excep­tions that are thrown on those threads, and with the Smart­Thread­Pool you can now do both!

// create new SmartThreadPool
var threadPool = new SmartThreadPool();
// queue up work items
var result = threadPool.QueueWorkItem(
    new Amib.Threading.Func<object, bool>(o => true), new object());
var exception = threadPool.QueueWorkItem(
    new Amib.Threading.Func<object, bool>(o => { throw new Exception(); }), new object());

// wait till the items are done
if (SmartThreadPool.WaitAll(new[] { result, exception }))
{
    Console.WriteLine(result.Result); // prints true
    try
    {
        Console.WriteLine(exception.Result); // throws exception
    }
    catch (Exception)
    {
        Console.WriteLine("Exception");
    }
}

Work items can have priority

The Smart­Thread­Pool allows you to spec­ify the pri­or­ity of the threads in the pool, so it’s pos­si­ble to have a thread pool for crit­i­cal jobs with higher pri­or­ity and a sep­a­rate thread pool for non-essential jobs which have a lower priority:

// create a STPStartInfo object and change the default values
var stpStartInfo = new STPStartInfo
    {
        DisposeOfStateObjects = true,
        MinWorkerThreads = 0,
        MaxWorkerThreads = 10,
        ThreadPriority = ThreadPriority.Lowest
    };
// create the SmartThreadPool instance
var threadPool = new SmartThreadPool(stpStartInfo);

Ref­er­ences:

SmartThreadPool’s Code­Plex homepage

MSDN arti­cle on man­ag­ing the thread pool

Share

There are a lot of dis­cus­sions on the pros and cons of using the Thread­Pool and cre­at­ing your own threads. Hav­ing spent a bit of time read­ing what oth­ers have to say, here’s a sum­mary of the things I’ve picked up on.

The prob­lem with cre­at­ing your own threads

Cre­at­ing and destroy­ing threads has a high CPU usage, so when you need to per­form lots of small, sim­ple tasks con­cur­rently the over­head of cre­at­ing your own threads can take up a sig­nif­i­cant por­tion of the CPU cycles and severely affect the final response time. This is espe­cially true in stress con­di­tions where exe­cut­ing mul­ti­ple threads can push CPU to 100% and most of the time would be wasted in con­text switch­ing (swap­ping threads in and out of the proces­sor along with their memory).

Using the Thread Pool

This is where the .Net Thread Pool comes in, where a num­ber of threads are cre­ated ahead of time and kept around to pick up any work items you give them to do, with­out the over­head asso­ci­ated with cre­at­ing your own threads.

When not to use the Thread Pool

In an ideal world you would always want to use the Thread Pool, but there are some real-world lim­i­ta­tions. Most impor­tantly, and the rea­son why most experts would tell you not to use the Thread Pool except for brief jobs is that: there is a lim­ited num­ber of threads in the .Net Thread Pool (250 per CPU by default), and they are being used by many of the .Net frame­work classes (e.g. timer events are fired on thread pool threads) so you wouldn’t want your appli­ca­tion to hog the thread pool.

There are also a num­ber of sit­u­a­tions where you shouldn’t use the thread pool:

  • You require a fore­ground thread, all the thread pool threads are back­ground threads
  • You require a thread to have a par­tic­u­lar priority.
  • You have tasks that cause the thread to block for long peri­ods of time. The thread pool has a max­i­mum num­ber of threads, so a large num­ber of blocked thread pool threads might pre­vent tasks from starting.
  • You need to place threads into a single-threaded apart­ment. All Thread­Pool threads are in the mul­ti­threaded apartment.
  • You need to have a sta­ble iden­tity asso­ci­ated with the thread, or to ded­i­cate a thread to a task.

Excep­tions in Thread Pool threads

Unhan­dled excep­tions on thread pool threads ter­mi­nate the process with 3 exceptions:

When to cre­ate your own threads

As I’ve men­tioned already, cre­at­ing your own threads is bad when lots of sim­ple tasks require a rel­a­tive large over­head in con­text switch­ing, and the Thread Pool is bad for long run­ning, or block­ing tasks. Which leads to the nat­ural con­clu­sion :-P – cre­ate your own threads for long run­ning, or block­ing tasks!

Part­ing thoughts…

When work­ing with the Thread Pool there are some use­ful meth­ods at your dis­pos­able, including:

  • GetAvail­ableThreads method which returns the num­ber of threads avail­able to you
  • Get­MinThreads method returns the num­ber of idle threads the thread pool main­tains in antic­i­pa­tion of new requests
  • Get­Max­Threads method returns the max num­ber of thread pool threads that can be active concurrently
  • Set­MinThreads method sets the num­ber of idle threads the thread pool main­tains in antic­i­pa­tion of new requests
  • Set­Max­Threads method sets the num­ber of thread pool threads that can be active concurrently

If you’re inter­ested in how the Thread­Pool class dynam­i­cally man­ages the size of the thread pool under the hood (despite giv­ing you the option to set min and max threads) you should have a read of Pedram Razai’s blog post in the ref­er­ence section.

And before you go, I men­tioned ear­lier that all Thread Pool threads are back­ground threads, so how do they dif­fer from fore­ground threads? Well, fore­ground and Back­ground threads are iden­ti­cal with one excep­tion: a back­ground thread does not keep the man­aged exe­cu­tion envi­ron­ment run­ning. Once all fore­ground threads have been stopped in a man­aged process (where the .exe file is a man­aged assem­bly), the sys­tem stops all back­ground threads and shuts down.

Ref­er­ences:

Stack­Over­flow ques­tion on Thread Pool vs Thread Spawning

Another Stack­Over­flow ques­tion on Thread Pool vs Thread Spawning

Stack­Over­flow ques­tion on when to use the Thread Pool in C#

Stack­Over­flow ques­tion on man­ag­ing the size of the Thread Pool in C#

Stack­Over­flow ques­tion with detail on the throt­tling behav­iour of the ThreadPool

MSDN arti­cle on The Man­aged Thread Pool

MSDN C# Pro­gram­ming Guide : how to use a ThreadPool

MSDN arti­cle on why we need a thread pool

Jon Skeet’s intro­duc­tory arti­cle on Multi-threading in C#

Pedram Rezaei’s blog post on ded­i­cated threads vs thread­pool threads

Smart Thread Pool project on CodePlex

Share

I found a nice usage of AOP the other day, using AOP to keep track of how long your method takes to exe­cute and log a warn­ing mes­sage if it takes longer than a thresh­old you sup­ply. You can con­fig­ure it to log exe­cu­tion times or only flag warn­ing entries when threshold’s been exceeded.

[Serializable]
[DebuggerStepThrough]
[AttributeUsage(AttributeTargets.Method)]
public sealed class LogExecutionTimeAttribute : OnMethodInvocationAspect
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(LogExecutionTimeAttribute));

    // If no threshold is provided, then just log the execution time as debug
    public LogExecutionTimeAttribute() : this (int.MaxValue, true)
    {
    }
    // If a threshold is provided, then just flag warnning when threshold's exceeded
    public LogExecutionTimeAttribute(int threshold) : this (threshold, false)
    {
    }
    // Greediest constructor
    public LogExecutionTimeAttribute(int threshold, bool logDebug)
    {
        Threshold = threshold;
        LogDebug = logDebug;
    }

    public int Threshold { get; set; }
    public bool LogDebug { get; set; }

    // Record time spent executing the method
    public override void OnInvocation(MethodInvocationEventArgs eventArgs)
    {
        var start = DateTime.Now;
        eventArgs.Proceed();
        var timeSpent = (DateTime.Now - start).TotalMilliseconds;

        if (LogDebug)
        {
            Log.DebugFormat(
                "Method [{0}{1}] took [{2}] milliseconds to execute",
                eventArgs.Method.DeclaringType.Name,
                eventArgs.Method.Name,
                timeSpent);
        }

        if (timeSpent > Threshold)
        {
            Log.WarnFormat(
                "Method [{0}{1}] was expected to finish within [{2}] milliseconds, but took [{3}] instead!",
                eventArgs.Method.DeclaringType.Name,
                eventArgs.Method.Name,
                Threshold,
                timeSpent);
       }
}
Share