I have code that grabs images from my mongodb database and then uploads it to my azure storage as seen below:
public async Task UploadAssetsAsync(Func<GridFSFileInfo, string> prefixSelector, List<GridFSFileInfo> files, Func<GridFSFileInfo, Task<Stream>> streamOpener, Func<string, Task> progressAction)
{
if (flyersContainerClient == null)
throw new Exception("Container client not initialized. Please initialize before doing blob operations.");
var q = new Queue<Task<Response<BlobContentInfo>>>();
progressAction?.Invoke($"{files.Count}");
foreach (var f in files)
{
var pathPrefix = prefixSelector(f);
var blobClient = flyersContainerClient.GetBlobClient($"{pathPrefix}/{f.Filename.Replace("_copy", "")}");
IDictionary<string, string> metadata = new Dictionary<string, string>();
var blobhttpheader = new BlobHttpHeaders();
if (f.Filename.EndsWith("svg"))
{
blobhttpheader.ContentType = "image/svg+xml";
}
var stream = await streamOpener(f);
if (pathPrefix == "thumbnails")
{
var format = ImageFormat.Jpeg;
Bitmap cropped = null;
using (Image image = Image.FromStream(stream))
{
format = image.RawFormat;
Rectangle rect = new Rectangle(0, 0, image.Width, (image.Width * 3) / 4);
cropped = new Bitmap(image.Width, (image.Width * 3) / 4);
using (Graphics g = Graphics.FromImage(cropped))
{
g.DrawImage(image, new Rectangle(0, 0, cropped.Width, cropped.Height), rect, GraphicsUnit.Pixel);
}
}
stream.Dispose();
stream = new MemoryStream();
cropped.Save(stream, format);
stream.Position = 0;
}
//await blobClient.SetMetadataAsync(metadata);
q.Enqueue(blobClient.UploadAsync(stream, new BlobUploadOptions { HttpHeaders = blobhttpheader, TransferOptions = new Azure.Storage.StorageTransferOptions { MaximumConcurrency = 8, InitialTransferSize = 50 * 1024 * 1024 } }));
//await blobClient.SetHttpHeadersAsync(blobHttpHeader);
}
await Task.WhenAll(q);
}
You can see what it is doing when the foreach starts with my list of files. I am also using an asyncronous task at the end that waits for all of my q
variables to finish as seen in the WhenAll
at the bottom. Would it benefit my code to use a Parallel.Foreach
for uploading my files or is there a faster way to achieve what I am doing?
Thanks for the help!