Is there a way to undo StorageFile.CopyAsync ()?

In Win8, I use somefile.CopyAsync (destFolder, newName) to copy files. But when I try to cancel it, it does not work. These two methods are how I try to cancel it:

  • just use IAsyncOperation.Cancel

    var op = somefile.CopyAsync(destFoder, newName);
    op.Cancel();
    op.Complete = (x,y) =>
    {
        switch(y) {
            case AsyncStatus.Complete:
                Debug.WriteLine("Completed" + x.GetResults().Name);
                break;
            case AsyncStatus.Cancel:
                Debug.WriteLine("Canceled")
                break;
        }
    }
    
  • use AsTask (CancellationToken)

    var cts = new CancellationTokenSource();
    cts.CancelAfter(TimeSpan.FromSeconds(1));
    var op = somefile.CopyAsync(destFolder, newName).AsTask(cts.Token);
    await op;
    

In the first method, the AsyncStatus.Cancel case is not called, and in the second method nothing happens too. Is there any other way that I can try? Thank!

+5
source share
1 answer

Have you tried this ...

var task = file.CopyAsync(KnownFolders.DocumentsLibrary, "test").AsTask();
task.AsAsyncAction().Cancel();

It worked in my simple test.

This code should work if you want to use cancel tokens

var source = new CancellationTokenSource(TimeSpan.FromMilliseconds(500));
var token = source.Token;
token.Register(() => { Debug.WriteLine("Your cancellation code here"); });
var task = file.CopyAsync(KnownFolders.DocumentsLibrary, "test").AsTask(token);
0
source

All Articles