Last active
February 13, 2019 04:34
-
-
Save vbjay/628c004184ce955a15a07d8e201377e0 to your computer and use it in GitHub Desktop.
Shows very basic downloading using async/await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Query Kind="VBProgram"> | |
<Reference><RuntimeDirectory>\Microsoft.VisualBasic.dll</Reference> | |
<Reference><RuntimeDirectory>\System.Net.Http.dll</Reference> | |
<Namespace>Microsoft.VisualBasic</Namespace> | |
<Namespace>System.Net.Http</Namespace> | |
<Namespace>System.Threading.Tasks</Namespace> | |
</Query> | |
Async Sub Main | |
Dim client As New HttpClient | |
Dim urls As String() = { | |
"https://geolite.maxmind.com/download/geoip/database/GeoLite2-City-CSV.zip", | |
"https://raw.githubusercontent.com/matthewreagan/WebstersEnglishDictionary/master/dictionary.json" | |
} | |
' client.GetByteArrayAsync(u) creates a task that is started right away. So the bytes are being downloaded right when it is called. | |
' So I am getting an array of objects that have a url and a Download property that is the download task | |
Dim downloads = urls.Select(Function(u) New With {.Url = u, .Download = client.GetByteArrayAsync(u)}).ToArray | |
downloads.Dump("Downloads") | |
Console.WriteLine("Files are downloading and awaiting all downloads here.") | |
' Files are downloading. This await creates a task that will continue the rest of main when all the downloads complete. | |
Await Task.WhenAll(downloads.Select(Function(d) d.Download)) | |
Console.WriteLine("Downloads are complete.") | |
'Downloads have completed. Since I am using linq I can't use await in the lambda. So I am getting the result property. | |
' The tasks have completed since we are in the continuation of the above await. | |
' Creates a projection from the tasks and creates an array of byte arrays. Dim data as byte()() | |
Dim data = downloads.Select(Function(d) d.download.Result).ToArray | |
'Create a projection from the byte arrays showing the size of each array. | |
' Notice that this does not show till the downloads complete | |
data.Select(Function(bd) New With { | |
.Size=bd.Length, | |
.Hash=String.Join("",array.ConvertAll(Sha512(bd),Function(b) b.ToString("X2"))) | |
}).Dump("Downloaded Data sizes") | |
End Sub | |
' Define other methods and classes here | |
Function Sha512(bytes As Byte()) As Byte() | |
Static sha As System.Security.Cryptography.SHA512Managed = System.Security.Cryptography.SHA512Managed.Create() | |
Return sha.ComputeHash(bytes) | |
End Function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Download and open in Linqpad