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.