jkickback
jkickback

Reputation: 13

Azure Storage Blob DownloadToStreamAsync WPF Threading

I'm trying to download multiple files from Azure Blob Storage for an updater application in WPF. I'm using Storage Client version 3.0 and trying to use the Async methods. I want to download the files and track the progress of each file, however, there is no IProgress overload for the DownloadToStreamAsync method. The other issue is that the file keeps downloadling (I know this because I'm watching the file grow in the temp directory), but the application things it's done immediately once it's starts the download. I'm a noob at multi-threading in .NET, so any help would be appreciated. Here's my code.

public async void Download()
{ 
    // Save blob contents to a file.
    using (FileStream fileStream = System.IO.File.OpenWrite(TempPath))
    {
        CloudBlockBlob blockBlob = Container.GetBlockBlobReference(BlobReference);    
        await blockBlob.DownloadToStreamAsync(fileStream);
    }
}

public void BeginDownload()
{
    Task task = new Task(Download);
    task.Start();
    task.Wait();
}

Upvotes: 1

Views: 1278

Answers (1)

i3arnon
i3arnon

Reputation: 116548

You should not be creating a task using new Task() You should get a task from the Download method:

public async Task DownloadAsync()
{ 
    // Save blob contents to a file.
    using (FileStream fileStream = System.IO.File.OpenWrite(TempPath))
    {
        CloudBlockBlob blockBlob = Container.GetBlockBlobReference(BlobReference);    
        await blockBlob.DownloadToStreamAsync(fileStream);
    }
}
public async Task BeginDownloadAsync()
{
    await DownloadAsync();
}

When you call an async void method you don't get a task to wait for so you can't be notified when the operation is completed. That's why it "finishes" before the operation is done. The BeginDownload method isn't really waiting for it to be done.

Upvotes: 2

Related Questions