gpt4 book ai didi

c# - 异步任务运行时如何更改进度条值

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:07 27 4
gpt4 key购买 nike

我正在使用异步等待任务来运行这段代码,我想在提取时更改进度条

public async Task<string> DownloadAndExtractFile(string source, string destination, string ItemDownload) //source = File Location //destination = Restore Location
{
string zPath = @"C:\Program Files\7-Zip\7zG.exe";
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = zPath;
pro.Arguments = "x \"" + source + "\" -o" + destination;

await Task.Run(() =>
{
Restore.frmRestore.progressBar1.Value = 50; //already set to public
try
{
Process x = Process.Start(pro);
Task.WaitAll();
Restore.frmRestore.progressBar1.Value = 100;//already set to public
x.Close();
Console.WriteLine("Extract Successful.");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

}
);

return "Success";
}

任务运行时如何改变进度条值。这是错误“跨线程操作无效:从创建它的线程以外的线程访问控件‘progressBar1’。”

最佳答案

Use the Progress<T> type to report progress ,正如我在我的博客中所描述的那样:

public async Task<string> DownloadAndExtractFile(string source, string destination, string ItemDownload)
{
string zPath = @"C:\Program Files\7-Zip\7zG.exe";
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = zPath;
pro.Arguments = "x \"" + source + "\" -o" + destination;

IProgress<int> progress = new Progress<int>(
value => { Restore.frmRestore.progressBar1.Value = value; });

await Task.Run(() =>
{
progress.Report(50);
try
{
Process x = Process.Start(pro);
Task.WaitAll();
progress.Report(100);
x.Close();
Console.WriteLine("Extract Successful.");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
});
return "Success";
}

关于c# - 异步任务运行时如何更改进度条值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36568625/

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