Cancel a long operation

I have a background worker that works to copy a huge file (several GB), and I would like to know how to cancel the process in the middle of the copy. I can check the CancellationPending property before the copy, but I don’t know how to do it when the copy is already running.

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

Please advise, thanks!

+3
source share
5 answers

I am not sure, but I think it is File.Copysupported by the CopyFilewinapi function , which does not allow this function.

You must point to CopyFileExwhich allows you to use the callback method whenever a part of the file has been copied.

+6
+2

, . , , . , , . ( , , , , .)

0

. , .

, , dllimport CopyFileEx.

0

Instead of using File.Copyor any other copy function, you can also copy the file yourself (reading from the source stream, writing to the destination stream) in chunks. In the loop that is required to copy all the fragments, you can check whether the operation should be interrupted, and then perform the necessary operations to interrupt the copy process.

0
source

Source: https://habr.com/ru/post/1749933/


All Articles