从Task.Run异步更新进度条

时间:2017-03-29 13:38:50

标签: c# winforms asynchronous async-await

我有一种从用户信息生成软件激活密钥的方法:

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

        }

我有进度条。我想运行此方法异步并将进度更新到进度条。如何使用async-await方法更新UI。 BackgroundWorker是另类???

2 个答案:

答案 0 :(得分:11)

您应该使用更现代的IProgress<T> / Progress<T>类型:

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

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

这比Invoke要好,因为它不会将您的业务逻辑(GenerateAsync)与特定用户界面或任何用户界面绑定在一起。

答案 1 :(得分:4)

我在Winforms中使用此方法:

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