Eddie
Eddie

Reputation: 197

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!

Upvotes: 3

Views: 596

Answers (5)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Instead of using File.Copy or any other copy function, you could also copy the file yourself (reading from a source stream, writing to a destination stream) in chunks. In the loop required to copy all chunks you could check whether to abort the operation and then perform necessary operations to abort the copy process.

Upvotes: 0

Humberto
Humberto

Reputation: 7199

Copy the file in chunks. Between chunks, check if the operation has been cancelled.

This may smell like a wheel reinvention, but it's an option if you don't want to dllimport CopyFileEx.

Upvotes: 0

Don
Don

Reputation: 9661

The only way I know of is to use CopyFileEx (kernel32)

Upvotes: 2

Jack
Jack

Reputation: 133577

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.

Upvotes: 6

dlras2
dlras2

Reputation: 8486

As far as I know, background workers are best for running lots of little operations. I know it's messy, but you might want to look into creating a separate thread for your copy operation. That way, if you're in the middle of copying, you can just kill the thread. (I'm not sure what this would do to the copying, tho - I don't know if it would leave a temporary file behind using this method.)

Upvotes: 0

Related Questions