Task.wait not working as I imagined

Posted by user2357446 on Stack Overflow See other posts from Stack Overflow or by user2357446
Published on 2014-08-22T16:15:14Z Indexed on 2014/08/22 16:20 UTC
Read the original article Hit count: 189

Filed under:
|
|

I am trying to download a file, wait for the file to finish downloading, and then read the file afterwards. I have the following methods to do this:

private async Task startDownload(string link, string savePath)
{      
        WebClient client = new WebClient();
        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
        client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
        await client.DownloadFileTaskAsync(new Uri(link), savePath);              
}

private void checkUpdateButton_Click(object sender, EventArgs e)
{           
    Task task = Task.Factory.StartNew(() => startDownload(versionLink, versionSaveTo));
    task.Wait();

    if (task.IsCompleted)
    {
        checkVersion();
    }
}

The checkVersion() method reads the file that was downloaded. This is throwing an IOException saying that the file is in use by something else and cannot be read. I thought that having task.Wait would prevent the rest of the method from executing until the task was finished?

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading