Search code examples
c#asp.netimagestreamprogress

Progress bar for a ImageStream doesn't show values from 0 to 1


I have a progress bar for a image download in my ASP.NET application. In a while loop is the following code, in which I divide the length of bytes from the current stream by the expected stream to get the desired progress:

if (ExpectedStreamSize.HasValue && _configSize.HasValue)
{
    var expected = ExpectedStreamSize + _configSize.Value;
    var progress = _stream.ReadPosition / (float) expected;
    var limitedProgress = progress > 1 ? 1 : progress;

    var epsilon = 0.001;
    if (!_lastReportedProgress.HasValue || _lastReportedProgress.Value + epsilon < limitedProgress)
        _onProgressChanged?.Invoke(limitedProgress);

    _lastReportedProgress = limitedProgress;
    LogToFile(limitedProgress);     // Logged to see the values
}

However, I expect values from 0 to 1. So from 0% to 100%. When I debug I get the following value assignments:

ExpectedStreamSize.HasValue = true
_configSize.HasValue = 1714

ExpectedStreamSize = 8700000     // 8.7 MB
_configSize.Value = 1714
--> expected: 8701714

_stream.ReadPosition = 1722
expected: 8701714   
--> progress = 0.000197892048

I logged the values for the limitedProgress, which are the following ones:

0,000197892
0,0001981219
0,0001983517
...
0,0004684135

But I need the values from 0,00019xxxx to 1,0 (so that I reach the 100%).

Can someone explain to me what I am doing wrong and how to get the correct progress status?


Solution

  • So I found the bug myself and fixed it.

    lastReportedProgress = limitedProgress of course belongs in the if loop, that's wrong otherwise.

    The upper solution would probably have worked, but the time expenditure would have been extreme, because too many intermediate steps are output and queried here. Now it works and the log also returns the values I imagined:

    0,001000033
    0,002000066
    ...
    0,9970638
    0,998064
    0,9990641
    

    I also adjusted the float value above to make the second condition in the if loop look better.

    private float _lastReportedProgress = 0;
    
    // some code 
    
        if(...)
        {
            if (_lastReportedProgress + epsilon < limitedProgress)
        }