On Thu, 29 Mar 2007 07:10:18 -0700, markon <ma****@gmail.comwrote:
I would like to run few lines of code and limit the time. If the
procedure would not be finished say in 1000ms I would like to stop
processing it.
Unfortunately I do not know where to begin to find resources how to do
it.
IMHO, the simplest solution is to use the DateTime class to keep track of
the time spent processing, checking it at a convenient place (or places)
in your processing (not too often, otherwise the checking the time will
start significantly slowing the processing itself down). When the time
spent exceeds the limit you have in mind, you exit your processing.
If you simply move the processing into another thread, you could stop the
processing by just terminating that thread but that's not a very clean way
to handle stopping the processing, and depending on the nature of the
processing may prevent you from being able to access a coherent set of
data representing the results of the processing (since you have no way to
control *where* in the processing the thread was terminated).
As an alternative to simply checking the time, you could use (for example)
interlocked access to a flag that is checked within the processing code
(in the same place or places you might check the time), run the processing
code in one thread and have a different thread monitoring the time. When
the time expires, the different thread would set the flag, the processing
code would notice that the flag has been set, and again exit cleanly.
(Actually, in practice you could probably get away without any
synchronized access to the flag, as long as the variable is marked
volatile, since the only change to the variable will ever to be to set the
flag).
The advantage of using a flag is that you can provide a number of
mechanisms to stop the processing, all of which use the event to signal
the thread to stop. You might have a thread monitoring the time (for
example, just set a timer on a form that expires when you want processing
to stop), and then also have a button on a form that the user can press to
stop processing.
Hope that helps.
Pete