异步方法“匿名"不应返回void [英] Asynchronous method 'anonymous' should not return void

查看:82
本文介绍了异步方法“匿名"不应返回void的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我解决这个问题吗? 我通常知道如何解决该问题,但不知道使用匿名方法. DelegateCommand有2个构造函数.

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)公共DelegateCommand(操作executeMethod)

1) public DelegateCommand (Action executeMethod)

2)公共DelegateCommand(操作executeMethod,Func canExecute).

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

我想知道是否有可能可以删除该警告.异步和等待是必需的,否则我的方法是:enterButtonClicked();将被同步调用.

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

    }
...

推荐答案

async await仅与Func<Task>Func<Task<T>>兼容(如果您没有),则您拥有被视为异步无效"的东西不应该.

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

}
...

这意味着enterButtonClicked引发的任何异常都不会被察觉

which means any exceptions raised by enterButtonClicked will go unnoticed

或使用支持异步功能的更好的委托命令.我个人喜欢 Nito.Mvvm.Async NuGet程序包中的AsyncCommand Stephen Cleary .

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

}
...

AsyncCommand委托在任务运行时将CanExecute设置为false,因此除非操作完成,否则人无法重复单击.

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

这篇关于异步方法“匿名"不应返回void的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆