Wait till the downloading is finished Windows phon

2019-04-17 00:35发布

问题:

How can i wait till the download operation is finished and want to return a status true or false back to UI .Now i am using Webclient for downloading image like this

 private async Task SaveCoversAsync(string CoverImageUrl)
{
WebClient getImageClient = new WebClient();
getImageClient.OpenReadCompleted += new OpenReadCompletedEventHandler(getImageClient_OpenReadCompleted);
getImageClient.OpenReadAsync(new Uri(CoverImageUrl), CoverImageUrl);
}

private async void getImageClient_OpenReadCompleted(object sender,   OpenReadCompletedEventArgs e)
{
try
{

    var storeFile = IsolatedStorageFile.GetUserStoreForApplication();
    string coverpath = string.Concat("filename.png");
    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(coverpath, System.IO.FileMode.Create, FileAccess.Write, FileShare.Write, storeFile))
    {
        byte[] buffer = new byte[1024];
        while (e.Result.Read(buffer, 0, buffer.Length) > 0)
        {
            stream.Write(buffer, 0, buffer.Length);
        }
    }
}
catch (Exception exe)
{

}

}

The problem is i cant use await , since i am using OpenReadCompleted event. How can i convert the above codebloack using WebClient.DownloadFileAsync? Or is there any wayt o wait till Download is over and return status

回答1:

While you can use HttpClient or WebClient to download files asynchronously, you should only do this for small files (eg pages or feeds). Doing so requires that the user keeps your application open for as long as the file transfer requires. That means, he doesn't close the phone, switch to another app or do anything that will cause the OS to pause your application.

The user won't be happy and your code will have to handle incomplete and interrupted downloads.

It is far better to use Background File Transfers. Essentially, you tell the OS what file you want to download, where you want to put it, and the OS takes care of downloading it in the background if possible, providing feedback about the transfer's process. The OS also checks for the status of the cellular or WiFi connection.

Check the sample in How to implement background file transfers for Windows Phone to see a two-page application that creates new BackgroundTransferRequest objects then tracks their progress.

The necessary code is rather simple. You create a new BackgroundTransferRequest object, set the paths and preferences (eg. use cellular or not) and pass it to BackgroundTransferService.Add for execution:

var transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
transferRequest.DownloadLocation = downloadUri;
if (wifiOnlyCheckbox.IsChecked == false)
{
  transferRequest.TransferPreferences = TransferPreferences.AllowCellular;
}
BackgroundTransferService.Add(transferRequest);

To track progress, you need to handle the request's events, TransferProgressChanged and TransferStatusChanged