© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
18 replies
Самке

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.

    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;
    }
    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;
    }



        progress.ProgressChanged += (sender, tuple) =>
        {
            latestProgress = tuple;
            Console.WriteLine($"index: {latestProgress.progressValue}    progress: {latestProgress.progressLong}");
        };
        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
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Progress bar problem
C#CC# / help
2y ago
✅ Problem updating rider
C#CC# / help
11mo ago
Problem updating Employee object
C#CC# / help
15mo ago
Updating Packages on old application problems
C#CC# / help
3y ago