Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8833207
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T08:43:30+00:00 2026-06-14T08:43:30+00:00

I’m having a hard time finding a task scheduler on which I can schedule

  • 0

I’m having a hard time finding a task scheduler on which I can schedule prioritised tasks but can also handle “wrapped” tasks. It is something like what Task.Run tries to solve, but you cannot specify a task scheduler to Task.Run.
I have been using a QueuedTaskScheduler from the Parallel Extensions Extras Samples to solve the task priority requirement (also suggested by this post).

Here is my example:

class Program
{
    private static QueuedTaskScheduler queueScheduler = new QueuedTaskScheduler(targetScheduler: TaskScheduler.Default, maxConcurrencyLevel: 1);
    private static TaskScheduler ts_priority1;
    private static TaskScheduler ts_priority2;
    static void Main(string[] args)
    {
        ts_priority1 = queueScheduler.ActivateNewQueue(1);
        ts_priority2 = queueScheduler.ActivateNewQueue(2);

        QueueValue(1, ts_priority2);
        QueueValue(2, ts_priority2);
        QueueValue(3, ts_priority2);
        QueueValue(4, ts_priority1);
        QueueValue(5, ts_priority1);
        QueueValue(6, ts_priority1);

        Console.ReadLine();           
    }

    private static Task QueueTask(Func<Task> f, TaskScheduler ts)
    {
        return Task.Factory.StartNew(f, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.DenyChildAttach, ts);
    }

    private static Task QueueValue(int i, TaskScheduler ts)
    {
        return QueueTask(async () =>
        {
            Console.WriteLine("Start {0}", i);
            await Task.Delay(1000);
            Console.WriteLine("End {0}", i);
        }, ts);
    }
}

The typical output of the example above is:

Start 4
Start 5
Start 6
Start 1
Start 2
Start 3
End 4
End 3
End 5
End 2
End 1
End 6

What I want is:

Start 4
End 4
Start 5
End 5
Start 6
End 6
Start 1
End 1
Start 2
End 2
Start 3
End 3

EDIT:

I think I’m looking for a task scheduler, similar to QueuedTaskScheduler, that will solve this problem. But any other suggestions are welcome.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T08:43:31+00:00Added an answer on June 14, 2026 at 8:43 am

    The best solution I could find is to make my own version of the QueuedTaskScheduler (original found in the Parallel Extensions Extras Samples source code).

    I added a bool awaitWrappedTasks parameter to the constructors of the QueuedTaskScheduler.

    public QueuedTaskScheduler(
            TaskScheduler targetScheduler,
            int maxConcurrencyLevel,
            bool awaitWrappedTasks = false)
    {
        ...
        _awaitWrappedTasks = awaitWrappedTasks;
        ...
    }
    
    public QueuedTaskScheduler(
            int threadCount,
            string threadName = "",
            bool useForegroundThreads = false,
            ThreadPriority threadPriority = ThreadPriority.Normal,
            ApartmentState threadApartmentState = ApartmentState.MTA,
            int threadMaxStackSize = 0,
            Action threadInit = null,
            Action threadFinally = null,
            bool awaitWrappedTasks = false)
    {
        ...
        _awaitWrappedTasks = awaitWrappedTasks;
    
        // code starting threads (removed here in example)
        ...
    }
    

    I then modified the ProcessPrioritizedAndBatchedTasks() method to be async

    private async void ProcessPrioritizedAndBatchedTasks()
    

    I then modified the code just after the part where the scheduled task is executed:

    private async void ProcessPrioritizedAndBatchedTasks()
    {
        bool continueProcessing = true;
        while (!_disposeCancellation.IsCancellationRequested && continueProcessing)
        {
            try
            {
                // Note that we're processing tasks on this thread
                _taskProcessingThread.Value = true;
    
                // Until there are no more tasks to process
                while (!_disposeCancellation.IsCancellationRequested)
                {
                    // Try to get the next task.  If there aren't any more, we're done.
                    Task targetTask;
                    lock (_nonthreadsafeTaskQueue)
                    {
                        if (_nonthreadsafeTaskQueue.Count == 0) break;
                        targetTask = _nonthreadsafeTaskQueue.Dequeue();
                    }
    
                    // If the task is null, it's a placeholder for a task in the round-robin queues.
                    // Find the next one that should be processed.
                    QueuedTaskSchedulerQueue queueForTargetTask = null;
                    if (targetTask == null)
                    {
                        lock (_queueGroups) FindNextTask_NeedsLock(out targetTask, out queueForTargetTask);
                    }
    
                    // Now if we finally have a task, run it.  If the task
                    // was associated with one of the round-robin schedulers, we need to use it
                    // as a thunk to execute its task.
                    if (targetTask != null)
                    {
                        if (queueForTargetTask != null) queueForTargetTask.ExecuteTask(targetTask);
                        else TryExecuteTask(targetTask);
    
                        // ***** MODIFIED CODE START ****
                        if (_awaitWrappedTasks)
                        {
                            var targetTaskType = targetTask.GetType();
                            if (targetTaskType.IsConstructedGenericType && typeof(Task).IsAssignableFrom(targetTaskType.GetGenericArguments()[0]))
                            {
                                dynamic targetTaskDynamic = targetTask;
                                // Here we await the completion of the proxy task.
                                // We do not await the proxy task directly, because that would result in that await will throw the exception of the wrapped task (if one existed)
                                // In the continuation we then simply return the value of the exception object so that the exception (stored in the proxy task) does not go totally unobserved (that could cause the process to crash)
                                await TaskExtensions.Unwrap(targetTaskDynamic).ContinueWith((Func<Task, Exception>)(t => t.Exception), TaskContinuationOptions.ExecuteSynchronously);
                            }
                        }
                        // ***** MODIFIED CODE END ****
                    }
                }
            }
            finally
            {
                // Now that we think we're done, verify that there really is
                // no more work to do.  If there's not, highlight
                // that we're now less parallel than we were a moment ago.
                lock (_nonthreadsafeTaskQueue)
                {
                    if (_nonthreadsafeTaskQueue.Count == 0)
                    {
                        _delegatesQueuedOrRunning--;
                        continueProcessing = false;
                        _taskProcessingThread.Value = false;
                    }
                }
            }
        }
    }
    

    The change of method ThreadBasedDispatchLoop was a bit different, in that we cannot use the async keyword or else we will break the functionality of executing scheduled tasks in the dedicated thread(s). So here is the modified version of ThreadBasedDispatchLoop

    private void ThreadBasedDispatchLoop(Action threadInit, Action threadFinally)
    {
        _taskProcessingThread.Value = true;
        if (threadInit != null) threadInit();
        try
        {
            // If the scheduler is disposed, the cancellation token will be set and
            // we'll receive an OperationCanceledException.  That OCE should not crash the process.
            try
            {
                // If a thread abort occurs, we'll try to reset it and continue running.
                while (true)
                {
                    try
                    {
                        // For each task queued to the scheduler, try to execute it.
                        foreach (var task in _blockingTaskQueue.GetConsumingEnumerable(_disposeCancellation.Token))
                        {
                            Task targetTask = task;
                            // If the task is not null, that means it was queued to this scheduler directly.
                            // Run it.
                            if (targetTask != null)
                            {
                                TryExecuteTask(targetTask);
                            }
                            // If the task is null, that means it's just a placeholder for a task
                            // queued to one of the subschedulers.  Find the next task based on
                            // priority and fairness and run it.
                            else
                            {
                                // Find the next task based on our ordering rules...                                    
                                QueuedTaskSchedulerQueue queueForTargetTask;
                                lock (_queueGroups) FindNextTask_NeedsLock(out targetTask, out queueForTargetTask);
    
                                // ... and if we found one, run it
                                if (targetTask != null) queueForTargetTask.ExecuteTask(targetTask);
                            }
    
                            if (_awaitWrappedTasks)
                            {
                                var targetTaskType = targetTask.GetType();
                                if (targetTaskType.IsConstructedGenericType && typeof(Task).IsAssignableFrom(targetTaskType.GetGenericArguments()[0]))
                                {
                                    dynamic targetTaskDynamic = targetTask;
                                    // Here we wait for the completion of the proxy task.
                                    // We do not wait for the proxy task directly, because that would result in that Wait() will throw the exception of the wrapped task (if one existed)
                                    // In the continuation we then simply return the value of the exception object so that the exception (stored in the proxy task) does not go totally unobserved (that could cause the process to crash)
                                    TaskExtensions.Unwrap(targetTaskDynamic).ContinueWith((Func<Task, Exception>)(t => t.Exception), TaskContinuationOptions.ExecuteSynchronously).Wait();
                                }
                            }
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        // If we received a thread abort, and that thread abort was due to shutting down
                        // or unloading, let it pass through.  Otherwise, reset the abort so we can
                        // continue processing work items.
                        if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload())
                        {
                            Thread.ResetAbort();
                        }
                    }
                }
            }
            catch (OperationCanceledException) { }
        }
        finally
        {
            // Run a cleanup routine if there was one
            if (threadFinally != null) threadFinally();
            _taskProcessingThread.Value = false;
        }
    }
    

    I have tested this and it gives the desired output. This technique could also be used for any other scheduler. E.g. LimitedConcurrencyLevelTaskScheduler and OrderedTaskScheduler

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a jquery bug and I've been looking for hours now, I can't
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I would like to run a str_replace or preg_replace which looks for certain words
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.