Asynchronous method 'anonymous' should not return void

巧了我就是萌 提交于 2019-12-11 01:36:09

问题


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()
    {

    }
...

回答1:


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.



来源:https://stackoverflow.com/questions/46353690/asynchronous-method-anonymous-should-not-return-void

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!