Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update progress bar from Task.Run async

I have a method to generate software activation key from User Information:

private async void GenerateAsync()
        {
            await Task.Run(() =>
            {
                var secretstring = "CustomerName >> " + txtFullname.Text + " >> " + txtproducid.Text;
                keymng = new KeyManager(secretstring);
                var dateexp = numExpdate.Value;
                if (dateexp == 0)
                {
                    dateexp = 730000;
                }

                if (cbLicenseType.SelectedIndex == 0)
                {
                    kvc = new KeyValueClass()
                    {
                        LicenseType = LicenseType.FULL,
                        Header = Convert.ToByte(9),
                        Footer = Convert.ToByte(6),
                        ProductCode = PRODUCTCODE,
                        Edition = (Edition)Enum.Parse(typeof(Edition), cbEdition.SelectedText),
                        Version = 1,
                        Expiration = DateTime.Now.AddDays(Convert.ToInt32(dateexp))
                    };

                    if (!keymng.GenerateKey(kvc, ref productkey))
                    {
                        //Handling Error
                    }
                }
                else
                {
                    kvc = new KeyValueClass()
                    {
                        LicenseType = LicenseType.TRIAL,
                        Header = Convert.ToByte(9),
                        Footer = Convert.ToByte(6),
                        ProductCode = PRODUCTCODE,
                        Edition = (Edition)Enum.Parse(typeof(Edition), cbEdition.SelectedText),
                        Version = 1,
                        Expiration = DateTime.Now.AddDays(Convert.ToInt32(dateexp))
                    };
                    if (!keymng.GenerateKey(kvc, ref productkey))
                    {
                        //Handling Error
                    }
                }
            });

        }

and I have progressbar. I want to run this method async and update progress to progressbar. How to update UI with async-await method. BackgroundWorker is alternative???

like image 923
alextran Avatar asked Mar 29 '17 13:03

alextran


Video Answer


2 Answers

You should use the more modern IProgress<T>/Progress<T> types:

var progress = new Progress<int>(value => { progressBar.Value = value; });
await Task.Run(() => GenerateAsync(progress));

void GenerateAsync(IProgress<int> progress)
{
  ...
  progress?.Report(13);
  ...
}

This is better than Invoke because it doesn't tie your business logic (GenerateAsync) to a particular UI, or to any UI at all.

like image 170
Stephen Cleary Avatar answered Sep 23 '22 05:09

Stephen Cleary


I use this method in Winforms:

progressBar1.Invoke((Action)(() => progressBar1.Value=50))
like image 20
Bali C Avatar answered Sep 23 '22 05:09

Bali C