Limit number of Threads in Task Parallel Library

后端 未结 4 1628
悲&欢浪女
悲&欢浪女 2020-12-30 13:27

I have few hundreds of files i need to upload to Azure Blob Storage.
I want to use parallel task library.
But instead of running all the 100 threads to upload in a f

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 13:52

    You should not be using threads for this at all. There's a Task-based API for this, which is naturally asynchronous: CloudBlockBlob.UploadFromFileAsync. Use it with async/await and SemaphoreSlim to throttle the number of parallel uploads.

    Example (untested):

    const MAX_PARALLEL_UPLOADS = 5;
    
    async Task UploadFiles()
    {
        var files = new List();
        // ... add files to the list
    
        // init the blob block and
        // upload files asynchronously
        using (var blobBlock = new CloudBlockBlob(url, credentials))
        using (var semaphore = new SemaphoreSlim(MAX_PARALLEL_UPLOADS))
        {
            var tasks = files.Select(async(filename) => 
            {
                await semaphore.WaitAsync();
                try
                {
                    await blobBlock.UploadFromFileAsync(filename, FileMode.Create);
                }
                finally
                {
                    semaphore.Release();
                }
            }).ToArray();
    
            await Task.WhenAll(tasks);
        }
    }
    

提交回复
热议问题