我有一种从用户信息生成软件激活密钥的方法:
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是另类???
答案 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))