简体   繁体   中英

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???

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.

我在Winforms中使用此方法:

progressBar1.Invoke((Action)(() => progressBar1.Value=50))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM