Самке
Самке
CC#
Created by Самке on 7/7/2024 in #help
Updating progress on the screen problem
I am learning about asynchronous programming and i run into a problem with updating progress from async task. For some reason the task is doing its job correctly but the progress.ProgressChanged event doesn't update the progress on the screen correctly.
c#
public static async Task<long> CalculateSumAsync(int n, CancellationToken token, IProgress<(int, long)>? progress = null)
{
if (n <= 0)
{
throw new ArgumentOutOfRangeException(nameof(n));
}

long result = 0;

var res = await Task.Run(() =>
{
for (var i = 1; i <= n; i++)
{
result += i;

token.ThrowIfCancellationRequested();

progress?.Report((i, result));
}

return result;
});

return res;
}
c#
public static async Task<long> CalculateSumAsync(int n, CancellationToken token, IProgress<(int, long)>? progress = null)
{
if (n <= 0)
{
throw new ArgumentOutOfRangeException(nameof(n));
}

long result = 0;

var res = await Task.Run(() =>
{
for (var i = 1; i <= n; i++)
{
result += i;

token.ThrowIfCancellationRequested();

progress?.Report((i, result));
}

return result;
});

return res;
}
c#
progress.ProgressChanged += (sender, tuple) =>
{
latestProgress = tuple;
Console.WriteLine($"index: {latestProgress.progressValue} progress: {latestProgress.progressLong}");
};
c#
progress.ProgressChanged += (sender, tuple) =>
{
latestProgress = tuple;
Console.WriteLine($"index: {latestProgress.progressValue} progress: {latestProgress.progressLong}");
};
Result: Press C to exit Enter the number: 15 index: 1 progress: 1 index: 3 progress: 6 index: 3 progress: 6 index: 3 progress: 6 index: 3 progress: 6 index: 8 progress: 36 index: 9 progress: 45 index: 8 progress: 45 index: 10 progress: 55 index: 11 progress: 66 index: 15 progress: 120 index: 14 progress: 105 index: 6 progress: 21 Final result: 120 index: 13 progress: 91 index: 12 progress: 78
19 replies