gpt4 book ai didi

c# - 从 Task.Run async 更新进度条

转载 作者:行者123 更新时间:2023-11-30 18:56:15 25 4
gpt4 key购买 nike

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

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

}

我有进度条。我想异步运行此方法并将进度更新到进度条。如何使用异步等待方法更新 UI。 BackgroundWorker 是替代品???

最佳答案

您应该使用更现代的 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 ) 绑定(bind)到特定的 UI 或任何 UI。

关于c# - 从 Task.Run async 更新进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43095170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com