Preventing the application from leaving the file operation in the middle and exiting
I'm making something that writes data to a file. Now the problem I'm facing is that the application exits and the file writing operation is left hanging midway. As in I want a set of things to be either written completely or none. But the application开发者_Go百科 exits and only half of it is written sometimes. Any suggestions on what I'm doing wrong here? Thanks.
There isn't much to go on here... but...
Are you properly flushing your file stream?
It could be you're finishing your program just fine, but closing it before you're fully written.
try {
// Open file, start writing...
}
catch (Exception e)
{
// Close file and discard it (if that's what you want), log error with e.ToString()
}
// Close file
Let's take WinForm
as an example. When users click the X
button in the top-right corner(or some other buttons hence the exit), in the click event(or some other event like Form_Closing), check the status of the File_Operation_Thread(I assume you have such a Thread
/BackgroundWorker
to operate the file, otherwise your UI will be hanging). If the thread is running, show a dialog with Wait/Cancel button saying "The operation is being processing". The final implementation looks like:
BackgroundWorker worker = new BackgroundWorker();
void WriteButton_Clicked(object sender, EventArgs args)
{
//start writing to the file asynchronously, something like
//worker.DoWork += (s,e) => { /*writing to file*/ };
}
void ExitButton_Clicked(object sender, EventArgs args)
{
if (worker.IsBusy)
{
//show a dialog window
if (CANCEL)
{
worker.CancelAsync();
//but rolling the changes back is a nightmare!!
}
else
{
//exit the applcation when worker.RunWorkerCompleted
}
}
}
You probably have an exception that is caught and "eaten" by a try
/catch
block. Try to activate the handling of exceptions by the debugger (Debug->Exceptions->Common Language Runtime, and select both the check boxes).
精彩评论