Search code examples
wpfasync-awaitcontinuewith

Problem with running tasks sequentially using ContinueWith


I want to start a proccess by checking toggleButton and after finishing proccess toggleButton be Unchecked.

Here is my code.

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;
           }
}

BUT when I run code ToggleButton Unchecked immediately after checking.

Result :

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


Solution

  • Why are you using ContinueWith with await? It makes no sense since the remainder of OnToggleButtonClicked will be executed once the awaited Task has finished.

    Set the property, await the first Task and then await another Task and set the property back to 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;
    }