这个,贴什么har07,应该工作。如果你需要扩展你的方法一点点,我会尝试做这样的事情(尽管它没有进行测试,但应工作):
(评论重修后 - 与取消)
// first define Cancellation Token Source - I've made it global so that CancelButton has acces to it
CancellationTokenSource cts = new CancellationTokenSource();
enum Problem { Ok, Cancelled, Other }; // results of my Task
// cancelling button event
private void CancellButton_Click(object sender, RoutedEventArgs e)
{
if (this.cts != null)
this.cts.Cancel();
}
// the main method - I've described it a little below in the text
public async Task<Problem> DownloadFileFromWeb(Uri uriToDownload, string fileName, CancellationToken cToken)
{
try
{
using (Stream mystr = await DownloadFile(uriToDownload))
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
if (ISF.FileExists(fileName)) return Problem.Other;
using (IsolatedStorageFileStream file = ISF.CreateFile(fileName))
{
const int BUFFER_SIZE = 1024;
byte[] buf = new byte[BUFFER_SIZE];
int bytesread = 0;
while ((bytesread = await mystr.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
{
cToken.ThrowIfCancellationRequested();
file.Write(buf, 0, bytesread);
}
}
}
return Problem.Ok;
}
catch (Exception exc)
{
if (exc is OperationCanceledException)
return Problem.Cancelled;
else return Problem.Other;
}
}
// and download
private async void Downlaod_Click(object sender, RoutedEventArgs e)
{
cts = new CancellationTokenSource();
Problem fileDownloaded = await DownloadFileFromWeb(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute), "myfile.txt", cts.Token);
switch(fileDownloaded)
{
case Problem.Ok:
MessageBox.Show("File downloaded");
break;
case Problem.Cancelled:
MessageBox.Show("Download cancelled");
break;
case Problem.Other:
default:
MessageBox.Show("Other problem with download");
break;
}
}
我添加了取消令牌 - 这意味着您的下载操作可以在Button.Click后取消。另一方面,如果等待DownloadFile(uriToDownload)被取消,它会自动抛出OperationCancelled - 然后你捕获该异常并返回足够的结果。
我还没有运行该代码,但它可能会显示主要想法。
在Windows Phone 8中的'WebClient'支持异步编程(见** TaskAsync **后缀方法)。但是,[HttpClient类](http://msdn.microsoft.com/library/system.net.http.httpclient.aspx)可以从[Microsoft HTTP Client Libraries](https:// www。 nuget.org/packages/Microsoft.Net.Http)** NuGet **包更适合异步编程。你的代码将变得更加干净。返回异步方法的Task也应该加后缀** Async **(已经有** Async **后缀方法的'WebClient'例外)。 –