1

Environment - C#, .NET 4.0, WPF, VS2010

I have an app that uses a keyboard hook to detect when a combination of four keys is pressed. When this occurs it calls Configuration.Save(), which has a call to myConfigDataSet.WriteXml(myConfigFile). And then on the next line it calls App.Current.Shutdown().

About half the time it works as expected. But many times it would insert XML content right into the middle of a previously existing configuration file, resulting in corrupt data.

I was able to fix the above issue by using...

if(File.Exists(myConfigFile)) { File.Delete(myConfigFile) }

...on the line just above the call to myConfigDataSet.WriteXml(myConfigFile)

But now many times it just writes a 0KB size file. I am pretty sure that all of my problems are being caused by App.Current.Shutdown() not waiting for the call to myConfigDataSet.WriteXml(myConfigFile) to finish.

Shouldn't this call block execution until the file has been written to disk? ...apparently not!!!

As a workaround I've already tried inserting Thread.Sleep(1000) to create a 1 second delay just before App.Current.Shutdown. But now sometimes the app errors out with a "StackOverFlow" exception...!!!

What would you guys recommend as a fix or workaround for this? What am I doing wrong?

Joey Powell
  • 89
  • 1
  • 5

2 Answers2

0

You can't stop a App.Current.Shutdown

Instead, use Application.Current.MainWindow.Close(). In this case, you can intercept in the Close event, process what you need to process, and then you could call App.Current.Shutdown

Fabske
  • 2,106
  • 18
  • 33
0

You can try to put the call to myConfigDataSet.WriteXml(myConfigFile) in a try/finally block. The finally block is executed completely even when the thread is aborted (see here). Not sure if it works with App.Current.Shutdown though.

So instead of:

myConfigDataSet.WriteXml(myConfigFile)

Do the following:

try {
    // Empty...
} finally {
    myConfigDataSet.WriteXml(myConfigFile)
}
Maarten
  • 22,527
  • 3
  • 47
  • 68