I've managed to implement a Task in my class that downloads a file from my webspace using normal HTTP. That is how I do it:
public async Task DownloadPackageTaskAsync(IProgress<int> progress)
{
var webRequest = WebRequest.Create(new Uri("http://ift.tt/1Cx3LkH"));
using (var webResponse = webRequest.GetResponse())
{
var buffer = new byte[1024];
FileStream fileStream = File.Create("Path"));
using (Stream input = webResponse.GetResponseStream())
{
if (input == null) throw new Exception("Error while getting the input.");
int received = 0;
double total = 0d;
var size = GetFileSize(new Uri("...")); // Gets the content length with a request as the Stream.Length-property throws an NotSupportedException
if (size != null) total = (long) size.Value;
int size = input.Read(buffer, 0, buffer.Length);
while (size > 0)
{
fileStream.Write(buffer, 0, size);
received += size;
progress.Report((received/total)*100));
size = input.Read(buffer, 0, buffer.Length);
}
}
}
}
This works well, the file is being downloaded and also if I add Debug.Print((received/total)*100) it outputs the correct percentage, everything is alright. The method is marked as async so that it can be awaited/wrapped asynchronously in a task. The problem occurs in another class that calls the method like that:
var downloadDialog = new UpdateDownloadDialog
{
LanguageName = _updateManager.LanguageCulture.Name,
PackagesCount = _updateManager.PackageConfigurations.Count()
};
_context.Post(downloadDialog.ShowModalDialog, null);
var progressIndicator = new Progress<int>();
progressIndicator.ProgressChanged += (sender, value) =>
downloadDialog.Progress = value;
_updateManager.DownloadPackageTaskAsync(progressIndicator);
It never calls the anonymous method there that should be invoked as soon as the progress changes, but nothing happens, I debugged it with breakpoints. Maybe I'm using the async-await-pattern wrong (again), I don't really know. Consecutively the UI does not update the progressbar it contains (which it does in the setter of the Progress-property that is initialized above).
I've read different articles but I did not find something that helped me. Help is appreciated.
Aucun commentaire:
Enregistrer un commentaire