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.
I use this method in Winforms:
progressBar1.Invoke((Action)(() => progressBar1.Value=50))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With