How to run a Highest Priority Periodic Task in C# WPF?

Vishal2 Bansal 285 Reputation points
2025-09-22T08:33:20.5666667+00:00

In My C# WPF .NET Framework Program i have multiple works to do :-

  1. 5 System.Timers. Timer: 3 instances which check periodically for (1min,40 sec, 2 mins) respectively. They check and run for (internet fluctuation, some db query , some websocket auto reconnection).
  2. UI Thread : Responsible to render my content etc on UI.
  3. A Thread(eka itemScheduler) (which must runs for 1 mins strictly without a single miss). Actually it checks for next content to play every 1 mins.
  4. Now the issue is during some internet downtime etc some timers methods are taking longer time and the itemScheduler named thread is not firing and missing at some time instances(I noticed during that time either of System Timers etc were running mostly/ UI Related work was happening.).
  5. Due to this Since itemScheduler thread is critical so due to it's miss we aren't able to play some contents which were scheduled for certain time only.

So do their have any better way to achieve it?

Developer technologies | Windows Presentation Foundation
{count} votes

Answer accepted by question author
  1. Danny Nguyen (WICLOUD CORPORATION) 3,500 Reputation points Microsoft External Staff
    2025-09-23T07:50:52.2066667+00:00

    Hi @Vishal2 Bansal ,

    Thanks for sharing your setup and concern about missed executions in your critical itemScheduler. To help ensure this periodic task runs reliably, consider the following:

    1. Dedicated High-Priority Thread:
      Run your scheduler on its own thread with ThreadPriority.Highest to minimize interference from other timers and UI tasks.
      Example:
         var schedulerThread = new Thread(() =>
         {
             while (true)
             {
                 RunSchedulerTask();
                 Thread.Sleep(TimeSpan.FromMinutes(1));
             }
         });
         schedulerThread.Priority = ThreadPriority.Highest;
         schedulerThread.IsBackground = true;
         schedulerThread.Start();
      
      You can read more about timer best practices in .NET and about thread priorities.
    2. Avoid Thread Pool Timers:
      Use a dedicated thread for critical timing, as thread pool timers can be delayed under heavy load.
    3. Keep Other Tasks Non-Blocking:
      Make sure your other periodic checks (internet, DB, websocket) don’t block or consume excessive resources.
    4. Monitor Execution:
      Log actual run times to help spot and troubleshoot missed intervals.

    Hope this helps. Feel free to reach out if you need any clarification.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Starry Night 600 Reputation points
    2025-09-24T09:05:02.6733333+00:00

    In C#, each thread has a priority that determines how frequently it gets access to the CPU. The Thread.Priority property is used to get or set the scheduling priority of a thread. The priority of a thread can be set to one of the values defined in the ThreadPriority enumeration: HighestAboveNormalNormalBelowNormal, and Lowest.

    When a thread is created, it gets a default priority of ThreadPriority.Normal. You can change the priority of a thread by setting the Priority property. Here is an example:

    using System;
    using System.Threading;
    class Program
    {
       static void Main(string[] args)
       {
           Thread thread1 = new Thread(SomeMethod) { Name = "Thread 1", Priority = ThreadPriority.Normal };
           Thread thread2 = new Thread(SomeMethod) { Name = "Thread 2", Priority = ThreadPriority.Lowest };
           Thread thread3 = new Thread(SomeMethod) { Name = "Thread 3", Priority = ThreadPriority.Highest };
           Console.WriteLine($"Thread 1 Priority: {thread1.Priority}");
           Console.WriteLine($"Thread 2 Priority: {thread2.Priority}");
           Console.WriteLine($"Thread 3 Priority: {thread3.Priority}");
           thread1.Start();
           thread2.Start();
           thread3.Start();
           Console.ReadKey();
       }
       public static void SomeMethod()
       {
           for (int i = 0; i < 3; i++)
           {
               Console.WriteLine($"Thread Name: {Thread.CurrentThread.Name} Printing {i}");
           }
       }
    }
    
    

    Impact of Thread Priority

    Thread priority influences how threads are scheduled by the operating system. However, it does not guarantee that a high-priority thread will always execute before a low-priority thread. Factors such as context switching and the availability of shared resources can affect the actual execution order.

    For example, if a high-priority thread is waiting for I/O operations, a lower-priority thread may get CPU time and complete its execution. This can lead to scenarios where a high-priority thread gets less CPU time than a low-priority thread over a specific period

    Example Demonstrating Thread Priority

    Here is an example that demonstrates how changing the priority of threads affects their

    using System;
    using System.Threading;
    class PriorityTest
    {
       static volatile bool loopSwitch = true;
       [ThreadStatic] static long threadCount = 0;
       public static void Main()
       {
           PriorityTest priorityTest = new PriorityTest();
           Thread thread1 = new Thread(priorityTest.ThreadMethod) { Name = "ThreadOne" };
           Thread thread2 = new Thread(priorityTest.ThreadMethod) { Name = "ThreadTwo", Priority = ThreadPriority.BelowNormal };
           Thread thread3 = new Thread(priorityTest.ThreadMethod) { Name = "ThreadThree", Priority = ThreadPriority.AboveNormal };
           thread1.Start();
           thread2.Start();
           thread3.Start();
           Thread.Sleep(10000);
           loopSwitch = false;
       }
       public void ThreadMethod()
       {
           while (loopSwitch)
           {
               threadCount++;
           }
           Console.WriteLine($"{Thread.CurrentThread.Name,-11} with {Thread.CurrentThread.Priority,11} priority has a count = {threadCount:N0}");
       }
    }
    

    In this example, three threads are created with different priorities. The threads increment a variable in a loop for 10 seconds. The output shows how the priority affects the count of each thread

    Important Considerations

    • ThreadStateException: Thrown if the thread has reached a final state, such as Aborted.
    • ArgumentException: Thrown if the value specified for a set operation is not a valid ThreadPriority value.
    • Operating System Scheduling: The operating system may not always honor the thread priority due to various factors.

    By understanding and using thread priorities effectively, you can optimize the performance of your multithreaded applications in C#.

    Refer:

    1. Thread.Priority Property
    2. Threads Priorities in C#
    3. C# Thread Priority in Multithreading.
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.