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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T23:32:57+00:00 2026-05-28T23:32:57+00:00

I’m having a bit of a problem finding out how to cancel this task

  • 0

I’m having a bit of a problem finding out how to cancel this task in C#. I don’t exactly have a strong understanding of handling threads and I’ve tried Googling for some simple code examples to help me out but I’ve gotten really no where. Here’s the piece of code I’m working on:

var tasks = urls.Select(url => Task.Factory.StartNew(
state =>
{
    using (var client = new WebClient())
    {

        lock (this)
        {

        // code to download stuff from URL

        }

    }
}, url)).ToArray();

    try
    {
       Task.WaitAll(tasks);
    }
    catch (Exception e)
    {
      textBox2.AppendText("Error: " + e.ToString());
    }

Where “urls” is an array of URLs. Is there a simple way to make it so that, when I click a button in my program, the downloading of the URLs is stopped completely? Also, the code snippet I pasted is in a function which backgroundWorker1 calls, which I suppose might make things a bit more complicated. (The reason why I have a backgroundWorker is so the UI doesn’t lock up while it’s downloading URLs.)

If that in any way is a bit confusing, here is an outline of what I was trying to achieve with my code:

  • I have an array of URLs, I’d like to download every URL asynchronously without locking up the UI.
  • I’d preferably like the user to stop the program from downloading URLs by clicking a button, pretty much cancelling the thread.
  • When the user clicks the button again, the program downloads the URLs all over again from that array.

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-05-28T23:32:57+00:00Added an answer on May 28, 2026 at 11:32 pm

    Don’t know if this is right way to do this or not, but I have been able to cancel tasks using the following code. I have created a form with ListBox and ProgressBar so I’m raising and handling ProgressChanged event of BackgroundWorker. Hope this helps you in some way.

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        CancellationTokenSource _tokenSource = new CancellationTokenSource();
        CancellationToken _token = _tokenSource.Token;
    
        var urls = e.Argument as IEnumerable<string>;
    
        _token = new CancellationToken();
    
        if (urls == null) return;
    
        var i = 0;
        var a = 100 / urls.Count();
    
        var sb = new StringBuilder();
        var t = urls.Select(url => Task.Factory.StartNew(
                        (u) =>{
                            using (var wc = new WebClient())
                            {
                                lock (this){
                                    var s = wc.DownloadString(u.ToString());
                                    sb.AppendFormat("{1}:{0}\r\n", "", u);
                                }
                            }
    
                        if (Worker.CancellationPending){
                            //MAGIC HAPPENS HERE, IF BackgroundWorker IS REQUESTED
                            //TO CANCEL, WE CANCEL CancellationTokenSource
                            _tokenSource.Cancel();
                        }
    
                        //IF CANCELATION REQUESTED VIA CancellationTokenSource
                        //THROW EXCEPTION WHICH WILL ADD TO AggreegateException
                        _token.ThrowIfCancellationRequested();
    
                        //YOU CAN IGNORE FOLLOWING 2 LINES
                        i += a;
                        Worker.ReportProgress(i, u);
        }, url, _token)).ToArray();
    
        try
        {
            Task.WaitAll(t);
        }
        catch (AggregateException age)
        {
            if (age.InnerException is OperationCanceledException)
                sb.Append("Task canceled");
        }
        catch (Exception ex)
        {
            sb.Append(ex.Message);
        }
    
        e.Result = sb;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a jquery bug and I've been looking for hours now, I can't
I have a French site that I want to parse, but am running into

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.