I have a app that is starting up a thread that runs the standard windows defrag utility. It also gives the user the option to cancel the defrag if they want to. Problem is if the thread defrag is running on is canceled is there any data loss or does it just do the last operation and then exit. For example the code goes something like this:
Code works exactly as it should, runs the defrag on a separate thread so my UI remains responsive. I'm just worried about the effect of the cancel on it, when you call a thread abort does the program running in the thread know it's being canceled and "cleanly" close? I don't want to abort a file move operation when it's defraging and end up with a corrupt file.
Dim myDefragThread As New System.Threading.Thread(AddressOf DefragmentHardDrive) Dim CancelDefrag As Boolean = False Private Sub DefragmentHardDriveBarButtonItem_ItemClick(ByVal sender As Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles DefragmentHardDriveBarButtonItem.ItemClick If DefragmentHardDriveBarButtonItem.Caption = "Defragment My Hard Drive" Then If DisplayDialogBoxForm("This will start a disk defragmentation which can take anywhere from 5 minutes to a couple hours. " _ "Your machine may run sluggish during the process but can still be used as normal. You can cancel the defrag if needed by " _ "selecting the Cancel Defragment menu item. Do you want to continue?", "Defragment Disk?", True, , True) = Windows.Forms.DialogResult.Yes Then CancelDefrag = False DefragmentHardDriveBarButtonItem.Caption = "Cancel Hard Drive Defragment" myDefragThread.Start() End If Else ' Cancel was clicked. Check if thread is running and if so cancel it. If myDefragThread.IsAlive Then myDefragThread.Abort() myDefragThread.Join() MsgBox("Defrag Canceled") End If DefragmentHardDriveBarButtonItem.Caption = "Defragment My Hard Drive" CancelDefrag = True End If End Sub Private Sub DefragmentHardDrive(ByVal stateInfo As Object) Try Dim myProcess As New Process myProcess.StartInfo.FileName = "C:\WINDOWS\system32\cmd.exe" myProcess.StartInfo.Arguments = "/c defrag c:" myProcess.StartInfo.ErrorDialog = True myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden myProcess.Start() myProcess.WaitForExit() MsgBox("Defrag Complete!") Catch ex As Exception ' Only want to show a error if there was a problem and defrag wasn't canceled. If CancelDefrag = False Then DisplayDialogBoxForm("There was a error during the disk defragmentation.", "Error During Task", False, , True) End Try