Jun 9 2011

Lost Priorities

A common practice when developing real-time systems is to elevate the priority of the host process. A misconception that is often held is that raising a processes priority will implicitly provide greater priority to threads spawned within the host process. In truth, this is only true for the main thread and has no impact on Threads that were spawned during host execution. To ensure new threads are synchronized with the host Process, you’ll need to perform the following:

Create a means of mapping between the two thread priority options. Below is an example of a simple mapping which could serve a number of application needs

public static ThreadPriority GetThreadPriority(this Process process)
{
    switch (process.PriorityClass)
    {
        case ProcessPriorityClass.AboveNormal:
            return ThreadPriority.AboveNormal;
        case ProcessPriorityClass.BelowNormal:
            return ThreadPriority.BelowNormal;
        case ProcessPriorityClass.High:
            return ThreadPriority.Highest;
        case ProcessPriorityClass.Idle:
            return ThreadPriority.Normal;
        case ProcessPriorityClass.Normal:
            return ThreadPriority.Normal;
        case ProcessPriorityClass.RealTime:
            return ThreadPriority.Highest;
        default:
            return ThreadPriority.Normal;
    }
}

Set the priority of each thread you expect to be mapped to the host processes priority

var _workerThread = new Thread(WorkerStart)
{
    IsBackground = true,
    Priority = Process.GetCurrentProcess().GetThreadPriority(),
    Name = "My Worker Thread"
};

That's it, use it in good health.

Tags: ,