C# 在wp7的后台从web下载文件
我正在用c语言为wp7编写一个应用程序:2页[主页,第二页]。C# 在wp7的后台从web下载文件,c#,silverlight,windows-phone-7,C#,Silverlight,Windows Phone 7,我正在用c语言为wp7编写一个应用程序:2页[主页,第二页]。 应用程序在mainpage中启动,然后用户可以在secondpage中导航到secondpage(使用NavigationService.navigate) 在secondpage中,WebClient在isolatedStorage中下载一个文件 我的问题是,当用户使用back键返回主页时,下载会冻结 有没有一种方法可以在后台实现这一点,这样用户就可以导航并自由地抛出页面 下面是secondpage类的代码(单击事件中还有一个带有
应用程序在mainpage中启动,然后用户可以在secondpage中导航到secondpage(使用NavigationService.navigate) 在secondpage中,WebClient在isolatedStorage中下载一个文件 我的问题是,当用户使用back键返回主页时,下载会冻结 有没有一种方法可以在后台实现这一点,这样用户就可以导航并自由地抛出页面 下面是secondpage类的代码(单击事件中还有一个带有webClient.OpenReadAsync(uri)的按钮)
查看-听起来这正是您完成需求所需要的。您查看了BackgroundWorker类了吗
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);
}
}
}
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"));
}