传递一个* Awaitable *匿名函数作为参数 [英] Passing an *Awaitable* Anonymous Function as a Parameter

查看:153
本文介绍了传递一个* Awaitable *匿名函数作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code第一。这就是我想要做的。我很接近,但我想我只是需要修复,我在UpdateButton方法定义的参数我的方式。

 专用异步无效UpdateButton(动作<布尔>后)
{
    如果(!等待后())
        ErrorBox.Text =错误消息发布。
}私人无效PostToTwitter()
{
    UpdateButton(异步()=>等待新TwitterAction()发表(你好,世界!));
}私人无效PostToFacebook()
{
    UpdateButton(异步()=>等待新FacebookAction()发表(你好,世界!));
}

不幸的是,!等待后()不因为工作的类型无效是不是awaitable。所以,问题是,我怎么定义我在这个方法的参数,以支持的 awaitable 的参数?

下面是TwitterAction()。邮报()如何被定义...

public虚拟异步任务<布尔>邮政(字符串MESSAGEID){...}


解决方案

 专用异步无效UpdateButton(Func键<任务<布尔>>后)
{
    如果(!等待后())
        ErrorBox.Text =错误消息发布。
}

- 编辑 -

  UpdateButton(()=>邮政(SS));私人异步无效UpdateButton(Func键<任务<布尔>>后)
{
    如果(!等待后())
        this.Text =错误消息发布。
}公共虚拟异步任务<布尔>邮政(字符串MESSAGEID)
{
    返回等待Task.Factory.StartNew(()=>真);
}

Code first. This is what I'm trying to do. I'm close, but I think I just need to fix the way I've defined my parameter in the UpdateButton method.

private async void UpdateButton(Action<bool> post)
{
    if (!await post())
        ErrorBox.Text = "Error posting message.";
}

private void PostToTwitter()
{
    UpdateButton(async () => await new TwitterAction().Post("Hello, world!"));
}

private void PostToFacebook()
{
    UpdateButton(async () => await new FacebookAction().Post("Hello, world!"));
}

Unfortunately, the !await post() doesn't work because, "Type 'void' is not awaitable." So the question is, how do I define my parameter in this method to support an awaitable parameter?

Here's how the TwitterAction().Post() is defined...

public virtual async Task<bool> Post(string messageId){...}

解决方案

private async void UpdateButton(Func<Task<bool>> post)
{
    if (!await post())
        ErrorBox.Text = "Error posting message.";
}

--EDIT--

UpdateButton(()=>Post("ss"));

private async void UpdateButton(Func<Task<bool>> post)
{
    if (!await post())
        this.Text = "Error posting message.";
}

public virtual async Task<bool> Post(string messageId)
{
    return await Task.Factory.StartNew(() => true);
}

这篇关于传递一个* Awaitable *匿名函数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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