如何在异步任务 运行 时更改进度条值

How to change progressbar value when async task running

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

public async Task<string> DownloadAndExtractFile(string source, string destination, string ItemDownload) //source = File Location //destination = Restore Location
    {
        string zPath = @"C:\Program Files-ZipzG.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";
    }

如何在任务 运行ning 时更改进度条值。这是错误 "Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on."

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

public async Task<string> DownloadAndExtractFile(string source, string destination, string ItemDownload)
{
  string zPath = @"C:\Program Files-ZipzG.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";
}

您可以使用 Progress<T>。这允许您通知 UI 线程您的进度并更新您的进度条。

因此,在调用该任务的地方,执行以下操作:

Progress<int> progress = new Progress<int>(i => Restore.frmRestore.progressBar1.Value = i);
await DownloadAndExtractFile(source, destination, ItemDownload, progress);

在您的方法中,您可以像这样使用 progress

public async Task<string> DownloadAndExtractFile(string source, string destination, string ItemDownload, IProgress<int> progress)
{
    // shortened for clarity
    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";
}

注意: 你必须将 progress 作为接口类型传递 IProgress<int> 才能访问该接口的 Report 方法.

直接解,但不像Progress<T>:

那么花哨

创建函数:

private void UpdateProgress(int percent)
{
  if (Restore.frmRestore.progressBar1.InvokeRequired)
  {
    UpdateProgress.Invoke(percent);
  }
  else
  {
    Restore.frmRestore.progressBar1.Value = percent;
  }
}

然后调用它而不是直接设置值。

澄清一下:.Invoke 确实在主线程(即 UI-线程)上执行函数。

这 1:1 你不想要的,但我会用 Progress<T>