Hi,
I have written a c# windowsapplication to convert an ASCII file.
First I select an input file-->with a button a method() reads and converts the content of the file (with for loops) and writes the new content to a new file.
How can I cancel this method() with a button?
When the methods() runs, I can't escape it or use the exit button of the form
Greetzzz,
G
Loading
Sam HobbsPosted Nov 20, 2010, 5:24 PM
Zoran HorvatPosted Nov 20, 2010, 2:31 PM
Gerben SchmidtPosted Nov 20, 2010, 2:21 PM
I use the async thread.
I also want to delete the written files that were cancelled
However when I break my loop that writes, with the if CancellationPending,
the last file is still open. how can I close this file?
I tried to close the files in this if statement that is breaking my for loop,
But then the form hangs....
if (bw_Async.CancellationPending)
{
// Pause for bit to demonstrate that there is time between
// "Cancelling..." and "Canceled".
Thread.Sleep(1200);
//Close file that is cancelled
fileout.Close();
// Set the e.Cancel flag so that the WorkerCompleted event
// knows that the process was canceled.
e.Cancel = true;
return;
}
Someone got an idea?
Sam HobbsPosted Nov 18, 2010, 9:46 PM
Zoran HorvatPosted Nov 18, 2010, 5:57 PM
1. Run operation on a separate thread. This leaves main application thread responsive and ready to process button click and other GUI events.
2. Provide manual reset event to the function which performs operation (initially not set). Owner will set this event when operation should be stopped.
3. Implement button click event handler, and in that handler set the event. Then invoke Join method on the thread object which performs operation. This will wait for the thread to terminate.
4. Thread procedure which performs operation must check the event very often, e.g. once in every iteration. This is done using WaitOne method with timeout set to zero - in this case, method will exit immediately, returning true if event is set, i.e. thread should quit operation and terminate.
5. When terminating the operation, do not forget to cleanup unfinished work. For instance, you may want to delete incomplete file.