Search code examples
c#winformsprogress-barwindowsasyncfileupload

How to generate dynamic progress bar on windows form for parallel upload progress


I have to create a Windows application where i will upload multiple file to azure file share storage and i need to show the multiple file upload progress using progress bar control in windows for application.

I want to show the dynamic progress bar on windows form with each upload iteration of file upload.

Can any one suggest with sample loop iteration for upload with multiple file using progress bar on windows form.


Solution

  • Assuming you are referring to Blob Storage.

    UploadFromFileAsync(String, AccessCondition, BlobRequestOptions, OperationContext, IProgress, CancellationToken)

    A IProgress object to handle StorageProgress messages.

    StorageProgress Class

    Holds information about the progress data transfers for both request and response streams in a single operation.

    A nice little example on their site, allbeit a stream example

    CancellationToken cancellationToken = new CancellationToken();
    IProgress<StorageProgress> progressHandler = new Progress<StorageProgress>(
        progress => Console.WriteLine("Progress: {0} bytes transferred", progress.BytesTransferred)
        );
    
    await blob.UploadFromStreamAsync(
        srcStream,
        default(AccessCondition),
        default(BlobRequestOptions),
        default(OperationContext),
        progressHandler,
        cancellationToken
        );
    

    So where to from here. Because this is IO bound work its best not use Parallel.For or Parallel.ForEach its a waste of resources.

    However, ActionBlock Class in the TPL dataflow can be suited, or just async/await pattern with Task.WaitAll Method.

    Dataflow example

    var block = new ActionBlock<MySomething>(
        mySomething => MyMethodAsync(mySomething),
        new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 50 });
    
    foreach (var something in ListOfSomethings)
    {
        block.Post(something );
    }
    
    block.Complete();
    await block.Completion;
    

    So without writing the rest of the code for you

    1. Simply add up the size in bytes of your files before you start youy transfers.
    2. Create your progress handlers, and associate them with your tasks
      • Possibly keep the transferred amount with your tasks
    3. On progress (in thread safe manner) or just on a timmer (in a thread safe manner) sum your progress against the expected amount

    Obviously there are details left out of here, however you are now a programmer and its your mission (if you choose to accept it) to figure it out.. free lunch given, and i look forward to your next questions about everything in between :)