Search code examples
c#multithreadingbackgroundworkercancellation

Cancelling long operation


I have a background worker running to copy a huge file (several GBs) and I'd like to know how to cancel the process in the middle of the copy. I can check CancellationPending property before the copy but don't know how to do it when copy is already in progress.

if (worker.CancellationPending) // check cancellation before copy 
{   
    e.Cancel = true;
}
else
{    
    File.Copy("sourceFile", "destinationFile"); // need to cancel this
}

Please advise, thanks!


Solution

  • I'm not sure but I think that File.Copy is backed by the CopyFile function of the winapi that doesn't allow this feature.

    You should point toward CopyFileEx that allows a callback method whenever a portion of the file has been copied.