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 foreach on list of files, how can i put a limit on max number of threads that it can use and finish the job in parallel.
or does it balance the things automatically?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Did you try use MaxDegreeOfParallelism? Like this:
Essentially you're going to want to create an Action or Task for each file to upload, put them in a List, and then process that list, limiting the number that can be processed in parallel.
My blog post shows how to do this both with Tasks and with Actions, and provides a sample project you can download and run to see both in action.
With Actions
If using Actions, you can use the built-in .Net Parallel.Invoke function. Here we limit it to running at most 5 threads in parallel.
This option doesn't make use of the async nature of UploadFromFileAsync though, so you might want to use the Task example below.
With Tasks
With Tasks there is no built-in function. However, you can use the one that I provide on my blog.
And then creating your list of Tasks and calling the function to have them run, with say a maximum of 5 simultaneous at a time, you could do this:
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 withasync/await
andSemaphoreSlim
to throttle the number of parallel uploads.Example (untested):
You can find out by running this:
As you can see the number of parallelism is smaller at the start, gets bigger, and grows smaller towards the end. So there definitely is some sort of automatic optimization going on.