Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call an async command with a view model?

I have this code and I am wanting to move it into a view model:

resetButton.Clicked += async (sender, e) =>
{
   if (App.totalPhrasePoints < 100 || await App.phrasesPage.DisplayAlert(
                "Reset score",
                "You have " + App.totalPhrasePoints.ToString() + " points. Reset to 0 ? ", "Yes", "No"))
      App.DB.ResetPointsForSelectedPhrase(App.cfs);
};

I realize I will need to set up something like this:

In my XAML code;

<Button x:Name="resetButton" Text="Reset All Points to Zero" Command="{Binding ResetButtonClickedCommand}"/>

And in my C# code:

private ICommand resetButtonClickedCommand;

public ICommand ResetButtonClickedCommand
{
   get
   {
      return resetButtonClickedCommand ??
      (resetButtonClickedCommand = new Command(() =>
      {

      }));

    }

But how can I fit the async action into a command?

like image 288
Alan2 Avatar asked Sep 08 '17 11:09

Alan2


People also ask

Can I call async method without await?

The current method calls an async method that returns a Task or a Task<TResult> and doesn't apply the Await operator to the result. The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete.

How call async method in MVC?

Implementing Asynchronous Methods in Asp.Net MVC The first thing to do is to add the async keyword to Action Method. If we use the async Keyword in Method, the Method must also use await Keyword. The return type of an async method must be void, Task or Task<T> we have used Task<T> in Action Method.

How do you call async method in page load?

How can I call a async method on Page_Load ? If you change the method to static async Task instead of void, you can call it by using SendTweetWithSinglePicture("test", "path"). Wait() . Avoid async void unless you are using it for events.


1 Answers

You can try something like this:

(resetButtonClickedCommand = new Command(async () => await SomeMethod()));

async Task SomeMethod()
{
    // do stuff
}
like image 52
MaticDiba Avatar answered Oct 14 '22 07:10

MaticDiba