Relay Command can execute and a Task

后端 未结 5 2088
故里飘歌
故里飘歌 2020-12-14 04:13

i want to start a task when a relay command is called, however i want to disable the button as long as that task is running

take this example

private         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 04:49

    I strongly recommend that you avoid new Task as well as Task.Factory.StartNew. The proper way to start an asynchronous task on a background thread is Task.Run.

    You can create an asynchronous RelayCommand easily using this pattern:

    private bool updateInProgress;
    private ICommand update;
    public ICommand Update
    {
      get
      {
        if (update == null)
        {
          update = new RelayCommand(
              async () =>
              {
                updateInProgress = true;
                Update.RaiseCanExecuteChanged();
    
                await Task.Run(() => StartUpdate());
    
                updateInProgress = false;
                Update.RaiseCanExecuteChanged();
              },
              () => !updateInProgress);
        }
        return update;
      }
    }
    

提交回复
热议问题