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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T18:24:46+00:00 2026-06-09T18:24:46+00:00

I obviously don’t know what I’m doing when it comes to parallel programming with

  • 0

I obviously don’t know what I’m doing when it comes to parallel programming with .NET 4.0. I have a simple Windows app that starts a task to do some mindless work (outputting numbers 1-1000). I put a substantial pause in half way through to simulate a long running process. While this long pause is taking place, if I hit the Stop button, its event handler calls the Cancel method of CancellationTokenSource. I don’t want to do any further processing (in this case, outputting a message) in the Stop button’s event handler until the canceled task is done with its current iteration. How do I do this? I tried using Task.WaitAll, etc in the Stop button’s event handler, but that just throws an unhandled AggregateException. Here’s the code which will help explain my problem if run as described above:

  private Task t;
  private CancellationTokenSource cts;

  public Form1()
  {
     InitializeComponent();
  }

  private void startButton_Click(object sender, EventArgs e)
  {
     statusTextBox.Text = "Output started.";

     // Create the cancellation token source.
     cts = new CancellationTokenSource();

     // Create the cancellation token.
     CancellationToken ct = cts.Token;

     // Create & start worker task.
     t = Task.Factory.StartNew(() => DoWork(ct), ct);
  }

  private void DoWork(CancellationToken ct)
  {
     for (int i = 1; i <= 1000; i++)
     {
        ct.ThrowIfCancellationRequested();

        Thread.Sleep(10);  // Slow down for text box outout.
        outputTextBox.Invoke((Action)(() => outputTextBox.Text = i + Environment.NewLine));

        if (i == 500)
        {
           Thread.Sleep(5000);
        }
     }
  }

  private void stopButton_Click(object sender, EventArgs e)
  {
     cts.Cancel();

     Task.WaitAll(t);  // this doesn't work :-(

     statusTextBox.Text = "Output ended.";
  }

  private void exitButton_Click(object sender, EventArgs e)
  {
     this.Close();
  }

Any help with this would be greatly appreciated. Thanks in advance.

  • 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-09T18:24:47+00:00Added an answer on June 9, 2026 at 6:24 pm

    You would normally just use Task.Wait (instead of WaitAll), as it’s a single task. and then handled the exception appropriately:

    private void stopButton_Click(object sender, EventArgs e)
    {
        cts.Cancel();
        try
        {
            t.Wait();  // This will throw
        }
        catch (AggregateException ae)
        {
           ae.Handle<OperationCanceledException>(ce => true);
        }
    
        statusTextBox.Text = "Output ended.";
    }
    

    When you cancel a Task, the OperationCanceledException will get wrapped into an AggregateException and be thrown as soon as you call Wait() or try to get the Task’s Result (if it’s a Task<T>).


    Purely for your information – This is one place, especially given what you’re doing here, where C# 5 simplifies things. Using the new async support, you can write this as:

    // No need for "t" variable anymore 
    // private Task t;
    
    
    private async void startButton_Click(object sender, EventArgs e)
    {
       statusTextBox.Text = "Output started.";
    
       // Create the cancellation token source.
       cts = new CancellationTokenSource();
    
       try
       {
          // Create & start worker task.
          await Task.Run(() => DoWork(cts.Token));
          statusTextBox.Text = "Output ended.";
       }
       catch(OperationCanceledException ce) 
       {
          // Note that we get "normal" exception handling
          statusTextBox.Text = "Operation canceled.";
       }
    }
    
    private void stopButton_Click(object sender, EventArgs e)
    {
       // Just cancel the source - nothing else required here
       cts.Cancel();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I obviously don't know what I'm doing. I have finally got this PowerShell command
Obviously it's early days, I do not know whether this is information that is
I obviously don't know where is the problem!, First I ask the client to
I obviously don't get this somewhere. I have created a UserControl, the bare bones
I don't seem to understand the purpose of XMLString::transcode(XMLCh*) and XMLString::transcode(char*) , because obviously
Don't really know how to formulate the title, but it should be pretty obvious
I have a class, lets call it 'Words', that reads a file and creates
I have some code that autofilters a worksheet based on either the first criteria,
I have an interesting conundrum. We have a site that is a completely separate
I'm writing a simple console client-server app using MSMQ. I'm attempting to run it

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.