异步任务运行时如何更改进度条值 [英] How to change progressbar value when async task running
本文介绍了异步任务运行时如何更改进度条值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用异步等待任务来运行此代码,并且我想在提取时更改进度条
i am using async await task to run this code and i want to change the progress bar when extracting
public async Task<string> DownloadAndExtractFile(string source, string destination, string ItemDownload) //source = File Location //destination = Restore Location
{
string zPath = @"C:Program Files7-Zip7zG.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'从创建它的线程以外的线程访问."
how to change the progressbar value when task running. this is the error "Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on."
推荐答案
使用 Progress
类型报告进度,正如我在我的博客中所描述的:
Use the Progress<T>
type to report progress, as I describe on my blog:
public async Task<string> DownloadAndExtractFile(string source, string destination, string ItemDownload)
{
string zPath = @"C:Program Files7-Zip7zG.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";
}
这篇关于异步任务运行时如何更改进度条值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文