使用 ContinueWith 按顺序执行 运行 个任务的问题

Problem with running tasks sequentially using ContinueWith

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

这是我的代码。

Proccess.xaml :

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

ProccessViewModel.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。

结果:

ToggleButton Checked
ToggleButton Unchecked
1
2
.
.
49999
50000
50001
.
.
100000

为什么要将 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;
}