Skip to content

Instantly share code, notes, and snippets.

@tugberkugurlu
Created December 14, 2016 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tugberkugurlu/6a3435062d9a02c6a0ec0c1850171dc2 to your computer and use it in GitHub Desktop.
Save tugberkugurlu/6a3435062d9a02c6a0ec0c1850171dc2 to your computer and use it in GitHub Desktop.
Percentage Progress from multiple sources which runs in sequence.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
namespace ConsoleApp7
{
public class MainProgressReporter : IProgress<double>
{
public void Report(double value) => Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
}
public class RatioAwareProgressReporter : IProgress<double>
{
private readonly int _alreadyMadeProgress;
private readonly int _percentageRatio;
private readonly IProgress<double> _progress;
public RatioAwareProgressReporter(int alreadyMadeProgress, int percentageRatio, IProgress<double> progress)
{
_alreadyMadeProgress = alreadyMadeProgress;
_percentageRatio = percentageRatio;
_progress = progress;
}
public void Report(double value) =>
_progress.Report(_alreadyMadeProgress + (_percentageRatio * value) / 100);
}
class Program
{
static void Main(string[] args)
{
Do(60000, new MainProgressReporter());
}
private static void Do(long totalLength, IProgress<double> progress)
{
var length1 = (long)Math.Floor(((double)(totalLength) * 25) / 100);
var length2 = (long)Math.Floor(((double)(totalLength) * 40) / 100);
var length3 = (long)Math.Floor(((double)(totalLength) * 35) / 100);
DoInner(length1, new RatioAwareProgressReporter(0, 25, progress));
DoInner(length2, new RatioAwareProgressReporter(25, 40, progress));
DoInner(length3, new RatioAwareProgressReporter(65, 35, progress));
}
private static void DoInner(long length, IProgress<double> progress)
{
var reportedProgresses = new List<double> { 0 };
var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(length));
var waitAmount = length / 100;
while (!cts.IsCancellationRequested)
{
var madeProgress = reportedProgresses.Last() + 1;
progress.Report(madeProgress);
reportedProgresses.Add(madeProgress);
Thread.Sleep(TimeSpan.FromMilliseconds(waitAmount));
}
if (!reportedProgresses.Any(x => x == 100))
{
progress.Report(100);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment