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

查看:23
本文介绍了异步方法“匿名"不应返回 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) public DelegateCommand(Action executeMethod)

1) public DelegateCommand (Action executeMethod)

2) public DelegateCommand (Action 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 仅与 FuncFunc 兼容如果你没有,那么你就有了你不应该做的异步无效".

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 包中的 AsyncCommandStephen 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天全站免登陆