Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why i'm getting error Cannot await 'void'?

Tags:

c#

.net

winforms

private Queue<string> _downloadUrls = new Queue<string>();

        private void downloadFile(IEnumerable<string> urls)
        {
            foreach (var url in urls)
            {
                _downloadUrls.Enqueue(url);
            }

            DownloadFile();
        }

        private async Task DownloadFile()
        {
            if (_downloadUrls.Any())
            {
                WebClient client = new WebClient();
                client.DownloadProgressChanged += ProgressChanged;
                client.DownloadFileCompleted += Completed;

                var url = _downloadUrls.Dequeue();
                string FileName = url.Substring(url.LastIndexOf("/") + 1,
                            (url.Length - url.LastIndexOf("/") - 1));

                await client.DownloadFileAsync(new Uri(url), "C:\\Test4\\" + FileName);
                return;
            }
        }

The error is on the line:

await client.DownloadFileAsync(new Uri(url), "C:\\Test4\\" + FileName);

How can i solve the error ? Why it happen ? I gave all the details i think.

I added the rest of the code maybe it needed.

like image 306
Moses Meteor Avatar asked Dec 31 '16 13:12

Moses Meteor


2 Answers

WebClient.DownloadFileAsync is an event-based API that predates Tasks and async/await. You'll want to await WebClient.DownloadFileTaskAsync instead.

like image 109
yaakov Avatar answered Sep 28 '22 02:09

yaakov


The await operator is applied to a task in an asynchronous method meaning you can await on methods that return a task.

WebClient.DownloadFileAsync does not return a Task but WebClient.DownloadFileTaskAsync does.

like image 32
adonthy Avatar answered Sep 28 '22 02:09

adonthy