0

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

Haukinger
  • 10,420
  • 2
  • 15
  • 28
stack CVL
  • 15
  • 6
  • Was hated for that sequential calls here: https://stackoverflow.com/questions/69442685/awaiting-tasks-in-order-and-not-in-parallel/69442887#69442887. As explained, `ContinueWith` didn't do what you expect it should do. From comment out of there, you can check that discussion: https://blog.stephencleary.com/2013/10/continuewith-is-dangerous-too.html. And the solution is to run tasks and await them **separately**, one by one, and set `isChecked` false only after all `await`ings. – Auditive Oct 11 '21 at 10:51
  • Where do `ToggleButton Checked` and `ToggleButton Unchecked` come from in the output? – Haukinger Oct 11 '21 at 10:52
  • @Haukinger - When isChecked= true; and then isChecked= flase; runs. – stack CVL Oct 11 '21 at 11:33
  • Why is `IsChecked` bound in `TwoWay` mode? It should follow the `isChecked` property, I suppose. – Haukinger Oct 11 '21 at 11:43

1 Answers1

1

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;
}
mm8
  • 163,881
  • 10
  • 57
  • 88