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?
Threading. Tasks namespaces. The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. The TPL dynamically scales the degree of concurrency to use all the available processors most efficiently.
Compared to the classic threading model in . NET, Task Parallel Library minimizes the complexity of using threads and provides an abstraction through a set of APIs that help developers focus more on the application program instead of focusing on how the threads will be provisioned.
Limit the degree of parallelism in C# In other words, the degree of parallelism is an integer that denotes the maximum number of tasks that will be executed at the same point in time to process a query. By default, the Parallel. For and Parallel. ForEach methods have no limit on the number of spawned tasks.
Third Party Liability (TPL) refers to the legal obligation of third parties (for example, certain individuals, entities, insurers, or programs) to pay part or all of the expenditures for medical assistance furnished under a Medicaid state plan.
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<string>();
// ... 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);
}
}
Did you try use MaxDegreeOfParallelism? Like this:
System.Threading.Tasks.Parallel.Invoke(
new Tasks.ParallelOptions {MaxDegreeOfParallelism = 5 }, actionsArray)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With