I.Step
I.Step

Reputation: 779

Asynchronous method 'anonymous' should not return void

Can someone help me resolve this problem I tried everything. I usually know how to resolve that problem but not with anonymous method. DelegateCommand has 2 constructors.

1) public DelegateCommand (Action executeMethod)

2) public DelegateCommand (Action executeMethod, Func canExecute).

I wanna know is it possible some how to remove that warning. Async and await are needed otherwise my method: enterButtonClicked(); would be called synchronously.

 ...
    public DelegateCommand EnterButton { get; set; }

    public StartPageViewModel()
    {
        Title = "title_black.png";
        PasswordPlaceholder = "Lozinka";

        EnterButton = new DelegateCommand( async () => { await enterButtonClicked();}); // <----- I am getting that warning here
    }

    public async Task enterButtonClicked()
    {

    }
...

Upvotes: 2

Views: 2743

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

async await is only compatible with Func<Task> or Func<Task<T>> if you don't have that then you have what is considered a "Async void" which you should not do.

Your two options are to not await the task

...
public DelegateCommand EnterButton { get; set; }

public StartPageViewModel()
{
    Title = "title_black.png";
    PasswordPlaceholder = "Lozinka";

    EnterButton = new DelegateCommand( () => { var temp = enterButtonClicked();}); 
}

public async Task enterButtonClicked()
{

}
...

which means any exceptions raised by enterButtonClicked will go unnoticed

or use a better delegate command that supports async functions. Personally I like the AsyncCommand from the Nito.Mvvm.Async NuGet package written by Stephen Cleary.

...
public AsyncCommand EnterButton { get; set; }

public StartPageViewModel()
{
    Title = "title_black.png";
    PasswordPlaceholder = "Lozinka";

    EnterButton = new DelegateCommand(enterButtonClicked); //you can just use a delegate, no method needed.
}

public async Task enterButtonClicked()
{

}
...

The AsyncCommand delegate sets CanExecute to false while the task is running so a person can't repeatedly click unless the action has completed.

Upvotes: 4

Related Questions