Newbie to C# with question about signals, interrupts, etc.

J

Jamey Bon

Here is what I am trying to do:

A button's click event contains some code that does some stuff and takes
about 3-4 seconds to complete. I want to be able to interrupt that code
(and branch to some different code) with a subsequent click of that same
button. As far as I can tell, a new click event (or any other UI event,
for that matter) cannot happen until the current click event code as
completed.

I am just starting to learn about coding my own events and handlers, but
it doesn't seem like any event will fire while the button click event is
working. So I need some mechanism for interrupting the code of the click
event when the button is pressed again.

I would greatly appreciate any help in getting pointed in the right
direction for approaching this problem.

Thank you,

JB
 
P

Peter Duniho

[...]
I am just starting to learn about coding my own events and handlers, but
it doesn't seem like any event will fire while the button click event is
working. So I need some mechanism for interrupting the code of the click
event when the button is pressed again.

You have a variety of options:

* Include a call to DoEvents somewhere in your processing code where
it will get called reasonably often, to allow messages to be pumped and
processed (be careful to monitor the state of your processing to ensure
that you don't create an infinitely recursive loop)

* Use a timer to provide intervals during which you can do some
processing for a short period of time and then allow control to return
back to the form.

* Use another thread to do your processing, which will allow the
form's UI thread to continue handling user input. Check out the
BackgroundWorker class for example.

I don't think either of the first two methods are particularly elegant,
but they do have the advantage that they avoid some of the issues raised
by having multiple threads (the first of which you'll probably run into is
when you try to execute a method on the form class from the worker
thread...see Invoke and BeginInvoke for the right way to do that).

There is a lot of message threads in this newsgroup regarding dealing with
threads and forms already, so you should use Google to look at those
first. Most of the questions you'll come up with initially are likely
already answered.

Pete
 

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