运行异步任务时如何更改进度栏值 [英] 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 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'从创建该线程的线程以外的线程访问。
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."
推荐答案
使用正如我在博客中所描述的那样,进度< T>
类型用于报告进度:
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 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";
}
这篇关于运行异步任务时如何更改进度栏值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文