Async / Await与WinForms ProgressBar - WinForms版本

时间:2013-12-17 08:42:16

标签: c# asynchronous progress-bar async-await

请参阅:http://codepaste.net/djw3cw了解代码

如果异步编程的async / await很快就会像Linq一样,我认为这个问题是Async/Await with a WinForms ProgressBar

的一个非平凡的扩展

尽管代码是最优的,但我会很高兴用代替代码的指针或答案。

问题是:如何使用asynch / await设置进度条。在过去,我成功使用了Dispatcher。

Please see: http://codepaste.net/djw3cw  for the code
What is done: a textbox has any text in it converted to an int, then when
"mybutton1" is clicked, work is done based on the int, for int ms (int = 
milliseconds).
During this time, a progressbar "myProgressBar" is shown for 
every tenth-percent step
When work is complete, the label/textblock controls are updated
But the below does not work right: the form simply freezes until the work is
complete.  How to fix it?
How to do this using Task-based Asynchronous Pattern (TAP) or Async/Await,
rather than a Dispatcher?

以下是相关代码的片段,不言自明。

 private void mybutton1_Click(object sender, RoutedEventArgs e)
    {
        myLabel.Content = myTextBox.Text;

        string myString = myTextBox.Text;

        bool result = Int32.TryParse(myString, out myInteger);

        if (result == true)
        {
        myTextblock.Text = "Success, thread will be delayed by: " +  myInteger.ToString() + " ms";

            //
            int CounterInteger = 0;
            for (int j = 0; j < myInteger; j++) // set # itt
            {

                Thread.Sleep(1); //do some work here

               // myClassDoWork1.Delay_DoWork(myInteger); //optional way to do work in another class...

                if (j % (myInteger / 10) == 0)  //display progress bar in 10% increments
                {

                    CounterInteger = CounterInteger + 10;
                     myProgressBar.Value = (double)CounterInteger; // won't work here in a parallel manner...must use Dispatcher.BeginInvoke Action 
                    //how to make this work using Async/Await?  see: https://stackoverflow.com/questions/17972268/async-await-with-a-winforms-progressbar

                }

            }
            ///
            /// // above does not work properly:  the form simply freezes until the work is complete.  How to fix it?
            ///


            myLabel.Content = "done, delayed work done successfully: in " + myInteger.ToString() + " milliseconds";
            myTextblock.Text = "done, delayed work done successfully: in " + myInteger.ToString() + " milliseconds";
            return;
        }
        else
        {
            myTextblock.Text = "Error, integer not entered, try again." + myTextBox.Text;
            myLabel.Content = "Error, integer not entered, try again.";
            return;
        }


    }

1 个答案:

答案 0 :(得分:5)

您的代码中没有asyncawait。您的UI线程阻塞的原因是因为您正在运行同步代码。

如果您要将CPU绑定代码推送到后台线程,请使用Task.Run。然后你可以从UI线程中await代码。

private async void mybutton1_Click(object sender, RoutedEventArgs e)
{
  myLabel.Content = myTextBox.Text;
  string myString = myTextBox.Text;
  bool result = Int32.TryParse(myString, out myInteger);

  if (result == true)
  {
    myTextblock.Text = "Success, thread will be delayed by: " +  myInteger.ToString() + " ms";
    IProgress<int> progress = new Progress<int>(value => { myProgressBar.Value = value; });
    await Task.Run(() =>
    {
      int CounterInteger = 0;
      for (int j = 0; j < myInteger; j++)
      {
        Thread.Sleep(1);
        if (j % (myInteger / 10) == 0)
        {
          CounterInteger = CounterInteger + 10;
          progress.Report(CounterInteger);
        }
      }
    }

    myLabel.Content = "done, delayed work done successfully: in " + myInteger.ToString() + " milliseconds";
    myTextblock.Text = "done, delayed work done successfully: in " + myInteger.ToString() + " milliseconds";
    return;
  }
  else
  {
    myTextblock.Text = "Error, integer not entered, try again." + myTextBox.Text;
    myLabel.Content = "Error, integer not entered, try again.";
    return;
  }
}