我正在使用异步等待任务来运行此代码,我想在提取时更改进度条
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";
}
Run Code Online (Sandbox Code Playgroud)
如何在任务运行时更改进度条值。这是错误“跨线程操作无效:从创建它的线程以外的线程访问控制‘progressBar1’。”
使用Progress<T>类型来报告进度,正如我在博客中所述:
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";
}
Run Code Online (Sandbox Code Playgroud)