简体   繁体   English

有没有办法取消StorageFile.CopyAsync()?

[英]Is there a way to cancel StorageFile.CopyAsync()?

In Win8, I use somefile.CopyAsync(destFolder, newName) to copy files. 在Win8中,我使用somefile.CopyAsync(destFolder,newName)来复制文件。 But when I try to cancel it, it appears doesn't work. 但是当我尝试取消它时,它似乎不起作用。 These two method are how I try to cancel it: 这两种方法是我尝试取消它的方法:

  1. just use IAsyncOperation.Cancel 只需使用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; } } 
  2. use AsTask(CancellationToken) 使用AsTask(CancellationToken)

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

In first method, case AsyncStatus.Cancel doesnt be called, and in second method, nothing happens too.Is there any other way I can try? 在第一种方法中,情况AsyncStatus.Cancel没有被调用,而在第二种方法中,没有任何反应。我还有其他方法可以尝试吗? Thanks! 谢谢!

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 as well if you want to use cancellation 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM