Calling Task and report progress from there with IProgress

T.Zacks 3,996 Reputation points
2021-04-30T06:15:19.423+00:00

From my Async function i am using IProgress interface to write status into textbox but not getting expected output. where i made the mistake in my code ? i am using winform project.

public async Task<int> Getdata(int i)
        {
            IProgress<string> progress = new Progress<string>(str =>
            {
                textBox1.Text = str;
            });

            await Task.Delay(90000);
            progress.Report("Task completed "+i.ToString());
            //return Task.FromResult(10);
            return 10;
        }

        private async void btnTask1_Click(object sender, EventArgs e)
        {
            List<Task<int>> tasks = new List<Task<int>>();

            for (int i = 0; i < 5; i++)
            {
                tasks.Add(Getdata(i + 1));
            }

            var result = await Task.WhenAll(tasks);
        }
Developer technologies | C#
{count} votes

Accepted answer
  1. T.Zacks 3,996 Reputation points
    2021-04-30T14:35:27.243+00:00

    See this code and it is working fine.

    public async Task<int> Getdata(int i)
            {
                IProgress<string> progress = new Progress<string>(str =>
                {
                    textBox1.Text = str;
                });
    
                await Task.Delay(90000);
                progress.Report("Task completed "+i.ToString());
                return 10;
            }
    
            private async void btnTask1_Click(object sender, EventArgs e)
            {
                List<Task<int>> tasks = new List<Task<int>>();
    
                for (int i = 0; i < 5; i++)
                {
                    tasks.Add(Getdata(i + 1));
                }
    
                var result = await Task.WhenAll(tasks);
            }
    
            private async void btnTask2_Click(object sender, EventArgs e)
            {
                var tasks = new List<Task<int>>();
                for (int ctr = 1; ctr <= 10; ctr++)
                {
                    int baseValue = ctr;
                    tasks.Add(Task.Factory.StartNew(b => (int)b * (int)b, baseValue));
                }
    
                var results = await Task.WhenAll(tasks);
    
                int sum = 0;
                for (int ctr = 0; ctr <= results.Length - 1; ctr++)
                {
                    var result = results[ctr];
                    textBox1.Text += result.ToString() + ((ctr == results.Length - 1) ? "=" : "+");
                    sum += result;
                }
                textBox1.Text += sum.ToString();
            }
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.