Terminating Method Execution

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi

I have an application that calls a method that takes a considerable amount
of time. In this method I show and hide forms from an object declared in the
same class using 'ShowForm' and 'HideForm' methods I have written in the
class. I am trying to add a 'Stop' button to allow the user to terminate the
method if there is a problem.

The solution I have been using at the moment is to start the method in a new
thread, then terminate the thread when the button is pressed which stops
execution immediately. The problem is that terminating the thread seems to
destroy the forms. Any call I make to the form after the thread has been
terminated gives the exception 'Error creating window handle'.

I am wondering if there is a better way to immediately stop a method from
executing (has to be instant).

Thanks in advance.
 
Forms can only be accessed by the thread they have been created on. If you
created these forms on the new thread then when you kill that thread you
kill the forms.

One way to do what you want is to use a procedure in the form that is called
from an event on the form and a form level variable that used for
notification of termination. The at the points in the procedure that you
want to check for termination the procedure should call Application.DoEvents
and then check the form level variable to see if a termination has been
requested. The cancel button on the form should set the form level variable
to the termination state so that when the procedure checks the variable it
knows to stop processing and do any clean up code.

Hope this helps

Robby
 
Hi

Cheers for response

I am slightly confused now because I create the form from the main thread. I
do this by creating an object which creates the form in question in its
constuctor. Then from the new thread, I call the objects 'ShowForm' method
(written by me). This all works fine, so it seems I can access the form from
another thread.

The problem arrises when I try this for a second time when I create a new
thread again. The behaviour seems to be like you cannot access a form that
has been LOADED in a different thread as opposed to CREATED.

Just to make things a little stranger, the object is located in a seperate
DLL. I have done this same thing with no problems using a DLL written in VB,
the problem only arrised when porting the code over to C#.
 
Back
Top