Threading question

B

Bruce W.1

As an exercise in threading I wrote a winforms program that checks to
see if links are good at a website. First it gets the web page then
parses out all the URL's to an arrayList.

It then displays the URL's in a dataGrid. Then it starts a new thread
for each URL using WebRequest.GetResponse. Each thread has a name
(number actually) corresponding to its position in the arrayList and
dataGrid. I iterate thru the arrayList using a foreach loop (C#) which
fires off each new thread.

To start each thread I create an instance of a class called 'Worker'
which checks each URL and puts its results in the dataGrid. This all
works fine.

I also have an Abort Button on my winform which is not working right.
Pressing the Abort Button sets a class member boolean called '_stop' to
true. In the aforementioned foreach loop it checks this boolean before
it makes a new thread. So in theory new threads should stop being
created when the Abort Button is pressed. The Abort Button doesn't
actually abort any threads, it just stops new ones.

The problem is that the Abort Button wouln't click until all the threads
are fired. The foreach loop just keeps cranking out new threads until
done. Then the program picks up the fact that I pressed the Abort
Button.

What can I do in the foreach loop to let me interupt it? I tried
inserting a Thread.Sleep(10) in the foreach loop but that didn't work.

Thanks for your help.
 
K

Kevin P. Fleming

Bruce said:
What can I do in the foreach loop to let me interupt it? I tried
inserting a Thread.Sleep(10) in the foreach loop but that didn't work.

The problem is that you are running in a loop on the UI thread, so you
can't respond to UI events until the loop completes. Calling Sleep()
won't do it either, because UI events won't get processed after the
Sleep(), your loop will just continue.

You can call DoEvents inside the loop to process UI events, but that has
potential problems because the user can (unintentionally) cause
recursion if you haven't programmed around it. Otherwise, your
thread-creation loop will have to be on its _own_ thread, so the UI
thread can be free to respond to mouse clicks or whatever else.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Threading Question 1
threading 6
stopping threads 2
about stopping threads and critical regions 1
Thread question 5
DataGrid Binding / Threading Slow Updates 1
Any Threading Gurus out there? 10
about Collections 1

Top