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 8310293
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T19:24:33+00:00 2026-06-08T19:24:33+00:00

All, I have a mathod called TaskSpin that runs the passed method on a

  • 0

All, I have a mathod called TaskSpin that runs the passed method on a background thread using TPL.

public TaskSpin(Func asyncMethod, object[] methodParameters)
{
    ...
    asyncTask = Task.Factory.StartNew<bool>(() => 
        asyncMethod(uiScheduler, methodParameters));

    asyncTask.ContinueWith(task =>
    {
        ...
        // Finish the processing update UI etc.
        ...
        if (isStacked && task.Status == TaskStatus.RanToCompletion)
            ProcessNextTask(dataGridViewSite);
    }
    ...
}

This routine is well established to fire off one method at-a-time, but I have recently been required to queue multiple methods and run them sequentially. To do this (aided by this answer) I have written the following button click event handler

private void buttonProcAllUrg_Click(object sender, EventArgs e)
{
    // Build the stacker.
    Dictionary<Func<TaskScheduler, object[], bool>, object[]> taskPair = 
        new Dictionary<Func<TaskScheduler, object[], bool>, object[]>();
    this.taskQueue = 
        new Queue<KeyValuePair<Func<TaskScheduler, object[], bool>, object[]>>();

    // Populate the stacker.
    foreach (DataGridViewRow row in this.DataGridViewDrg.Rows) 
    {
        KeyValuePair<Func<TaskScheduler, object[], bool>, object[]> task =
            new KeyValuePair<Func<TaskScheduler, object[], bool>, object[]>
            (BuildDrgDataForSite, DrgDataRowInfo(row.Index));     
        this.taskQueue.Enqueue(task); 
    }

    // Launch the queue.
    ProcessNextTask(this.DataGridViewDrg);
}

and the method ProcessNextTask is defined as

private void ProcessNextTask(DataGridView dataGridView) 
{     
    try     
    {
        // Queue empty.
        bIsStacked = true;
        if (this.taskQueue.Count <= 0)
        {
            bIsStacked = false;
            return;
        }

        // Launch new task.
        KeyValuePair<Func<TaskScheduler, object[], bool>, object[]> item = this.taskQueue.Dequeue();
        Task<bool> asyncBuildDataTask = null;
        TaskSpin(asyncBuildDataTask, uiScheduler, mainForm,
                    item.Key, item.Value, dataGridView,
                    "Process stack successfully executed", true, bIsStacked);
    }     
    catch(InvalidOperationException)    
    {
        // Nothing left in stack.
        bIsStacked = false;    
    }   
} 

This works fine, but after the first task has run and the ProcessNextTask is called for the second (or more times) from the continuation, the GUI becomes unresponsive. What can I do to ensure the UI thread is not blocked upon the second call?

Note. I have tried to launch the ProcessNextTask method on another thread using the UI thread synchronisation context

Task task = Task.Factory.StartNew(() =>
{
    ProcessNextTask(dataGridView);
}, CancellationToken.None, 
   TaskCreationOptions.LongRunning, 
   uiScheduler);

where TaskScheduler uiSchduler = TaskScheduler.FromCurrentSynchonisationContex();.

Edit: I have attampted to create a BlockingCollection to facilitate what I want to do based on @Reed Copsey’s answer below, but I have never done this and would welcome any advice here

BlockingCollection<Action<object[]>> taskQueue = 
    new BlockingCollection<Action<object[]>>();
foreach (DataGridViewRow row in this.DataGridViewDrg.Rows) 
{
    Action<object[]> tmpAction = del => 
        {AsyncBuildDrgDataForSite(DrgDataRowInfo(row.Index)); };
    taskQueue.Add(tmpAction);
}

Thanks for your time.

  • 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-08T19:24:35+00:00Added an answer on June 8, 2026 at 7:24 pm

    I would recommend thinking about this differently.

    If you’re trying to “stack jobs”, it’s typically better to rework the routine into a producer/consumer scenario. BlockingCollection<T> provides the proper framework for this, as it provides a thread safe queue which you can just use to add in your work items, and then create a task to process them (via GetConsumingEnumerable()). Once the items are done, you can update your UI, then restart the “producer” task as you add a new item, etc.

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

Sidebar

Related Questions

I have a method that I'm using to output all the class names in
I have a method called action() that deploys three threads. Each deployed thread or
Nearly all programming languages that support threading, have a method called join . I
All, I have a generic method called TaskSpin , in this method I launch
I have a method connection(int n) which gives me all the cells number that
All, I have a method that is currently used to invoke DLLs of return
All, I have a method that returns a List. This method is used to
All, I have a method that takes a date (YYYY-MM-DD H:M:S) from the database
Suppose that I have a method called doSomething() and I want to use this
I have method called SColl. This method invokes a webservice. When using parallel.invoke I

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.