【问题标题】:Problem with running tasks sequentially using ContinueWith使用 ContinueWith 顺序运行任务的问题
【发布时间】:2021-11-30 02:43:50
【问题描述】:

我想通过选中toggleButton来启动一个进程,并在完成进程后toggleButton被取消选中。

这是我的代码。

Process.xaml:

<ToggleButton Command="{Binding StartProccessCommand}" Content="Proccessing"  IsChecked="{Binding isChecked,Mode=TwoWay}"></ToggleButton>

ProcessViewModel.cs:

public class ProccessViewModel: BindableBase 
{
  private bool _isChecked = false;
  public bool isChecked
  {
     get { return _isChecked; }
     set { SetProperty(ref _isChecked, value); }
  }

  public DelegateCommand StartProccessCommand{ get; set; }
  
  public ProccessViewModel()
   {
      StartProccessCommand= new DelegateCommand(OnToggleButtonClicked);
   }

  public async void OnToggleButtonClicked()
    {
       await Task.Run(() => {

          isChecked= true;
      
          for (int i = 0; i < 50000; i++)
            {
              Console.WriteLine(i);
            }

       }).ContinueWith((x) =>
           {
              for (int i = 50000; i < 100000; i++)
               {
                 Console.WriteLine(i);
               }

              isChecked= false;
           }
}

但是当我在检查后立即运行代码 ToggleButton Unchecked。

结果:

选中切换按钮
未选中切换按钮
1
2
.
.
49999
50000
50001
.
.
100000

【问题讨论】:

  • 被讨厌的顺序调用在这里:stackoverflow.com/questions/69442685/…。正如所解释的,ContinueWith 没有做你期望它应该做的事情。从那里的评论中,您可以查看该讨论:blog.stephencleary.com/2013/10/…。解决方案是运行任务并逐个单独等待它们,并在所有awaitings 之后才将isChecked 设置为false。
  • ToggleButton CheckedToggleButton Unchecked 在输出中来自哪里?
  • @Haukinger - 当 isChecked=true;然后 isChecked=flase;运行。
  • 为什么IsChecked 绑定在TwoWay 模式下?我想它应该遵循isChecked 属性。

标签: wpf async-await continuewith


【解决方案1】:

您为什么将ContinueWithawait 一起使用?这是没有意义的,因为 OnToggleButtonClicked 的其余部分将在等待的 Task 完成后执行。

设置属性,等待第一个Task,然后等待另一个Task,并将属性设置回false

public async void OnToggleButtonClicked()
{
    isChecked = true;
    await Task.Run(() => {

        for (int i = 0; i < 50000; i++)
        {
            Console.WriteLine(i);
        }
    });

    await Task.Run(() =>
    {
        for (int i = 50000; i < 100000; i++)
        {
            Console.WriteLine(i);
        }
    });
    isChecked = false;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    相关资源
    最近更新 更多