c# - Download multiple files async and wait for all of them to finish before executing the rest of the code -
i trying download multiple files internet , await of them finish. c# console application running, no progress bar event handler should necessary. continues execute code though files have not been downloaded.
- 1.downloading files!
- 2.finished download file a
- 3.finished downloading files!
- 4.finished downloading file b
- 5.finished downloading file c
how await till async download files finished.
private void downloadmultiplefiles(list<documentobject> doclist) { foreach(var value in doclist){ try { using (webclient webclient = new webclient()) { string downloadtodirectory = @resources.defaultdirectory + value.docname; webclient.credentials = system.net.credentialcache.defaultnetworkcredentials; webclient.downloadfilecompleted += client_downloadfilecompleted; webclient.downloadfileasync(new uri(value.docurl), @downloadtodirectory); //add them local context.listoflocaldirectories.add(downloadtodirectory); } } catch (exception) { errors.printerror("failed download file: " + value.docname); } } }
the downloadfileasync
/downloadfilecompleted
members of webclient
use event-based asynchronous pattern. if want use async
, await
, should using task-based asynchronous pattern.
in case, should use downloadfiletaskasync
member, such:
private async task downloadfileasync(documentobject doc) { try { using (webclient webclient = new webclient()) { string downloadtodirectory = @resources.defaultdirectory + value.docname; webclient.credentials = system.net.credentialcache.defaultnetworkcredentials; await webclient.downloadfiletaskasync(new uri(value.docurl), @downloadtodirectory); //add them local context.listoflocaldirectories.add(downloadtodirectory); } } catch (exception) { errors.printerror("failed download file: " + value.docname); } } private async task downloadmultiplefilesasync(list<documentobject> doclist) { await task.whenall(doclist.select(doc => downloadfileasync(doc))); }
please note context.listoflocaldirectories.add
, errors.printerror
methods should threadsafe.
Comments
Post a Comment