[英]download file from web in background in wp7
我正在用C#為wp7編寫一個應用程序:2頁[主頁,第二頁]。
該應用程序從主頁開始,然后用戶可以導航到第二頁中的第二頁(使用NavigationService.Navigate)。
在第二頁中,WebClient在isolatedStorage中下載文件。
我的問題是,當用戶使用后退鍵返回首頁時,下載會凍結!
有一種方法可以在后台執行此操作,以便用戶可以自由導航並拋出頁面?
這是第二頁類的代碼(單擊事件中還有一個帶有webClient.OpenReadAsync(uri)的按鈕)。
public partial class SecondPage : PhoneApplicationPage
{
WebClient webClient = new WebClient();
IsolatedStorageFile Storage = IsolatedStorageFile.GetUserStoreForApplication();
public SecondPage()
{
InitializeComponent();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
if (e.Result != null)
{
string fileName = "download.txt";
IsolatedStorageFileStream f = new IsolatedStorageFileStream(fileName, System.IO.FileMode.Create, Storage);
long fileNameLength = (long)e.Result.Length;
byte[] byteImage = new byte[fileNameLength];
e.Result.Read(byteImage, 0, byteImage.Length);
f.Write(byteImage, 0, byteImage.Length);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
try
{
if (ProgressDownload.Value <= ProgressDownload.Maximum)
{
ProgressDownload.Value = (double)e.ProgressPercentage;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
謝謝
使用BackgroundWorker類,我會遇到以下問題:當我調用webClient.OpenReadAsync時,bw_doWork函數(代碼在下面)結束了,因為該調用是異步的! 因此,bw報告了completeEvent。
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri("http://foo.com/asd.txt"));
}
查看Background Transfer API-聽起來正是滿足要求所需要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.