我正在寫一個應用程序在c#wp7:2頁[mainpage,secondpage]。
應用程序從主頁面開始,然後用戶可以導航到第二頁中的第二頁(使用NavigationService.Navigate)。從wp7的背景下載網絡文件
第二頁WebClient在isolationStorage中下載文件。
我的問題是,當用戶使用後退鍵返回到主頁時,下載會凍結!
有一種方法可以在後臺執行此操作,以便用戶可以導航自由地扔頁面?
這裏是secondpage類的代碼(在click事件中也有一個帶有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"));
}
你檢查了BackgroundWorker類http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.95).aspx – 2012-02-19 19:57:26