Button to interupt a foreach loop?

D

Dave Spencer

Hi all,

New to this group and to C# in general (experienced in MFC). Anyway I have
a ListView and a foreach loop that is doing something to each item in the
list and updating the list on the screen. I have a button on the screen
that I'll call STOP that is supposed to stop the processing of the loop in
midstream. I have a bool global variable call bStop. The OnClick for the
stop button sets bStop to true. The loop checks the value of bStop at the
beginning of each loop and calls break if it is true. Problem is bStop is
never set to true until after the loop finishes. In C++ I could make a call
to a function that would use PeekMessage to loop through the message que and
Dispatch any Dialog messages so that the bStop value would be updated.
Don't know how to do this in C#. Any ideas.

Thanks in advance,
Dave
 
K

Kevin Aubuchon

You'll have to put your for loop in another thread. Either one explicitly
created by you, or a pool thread created via an asynchronous delegate. The
main thread can set the bool that the for loop can check and exit when set.

good luck,
kevin aubuchon
 
F

fd123456

Hi Dave,

Can you try inserting an Application.DoEvents() in your foreach loop?

Michel
 
D

Dave Spencer

I inserted a DoEvents() into the loop just before I check for the stop
variable as a couple of you have suggested. This never works if I hit the
stop button once but always works if I hit the stop button a second time.
Not sure I'm smart enough to implement one of the multiple thread solutions
but I may give it a try if I can't get this to work.

Thanks,
Dave
 
F

fd123456

Hi Dave,

Instead of inserting DoEvents() right before you check for the Stop
variable, insert it at the top of your method. DoEvents takes some
processing time and is executed (I believe) on a separate thread,
which means your check is executed concurrently with the beginning of
the events polling.

It still doesn't explain why the first event is ignored, but I suspect
it has to do with timing. You're not hooking the click handler to the
button manually, are you? (If you are, maybe you're doing it too late
in the code. Try bumping it up).

Michel.
 
D

Dave Spencer

That did it. I think it was just a timing issue as you suggested.

Thanks All
Dave
 

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

Top