C# - 返回一个值异步地 [英] C# - Return a value asychronously

查看:286
本文介绍了C# - 返回一个值异步地的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 私人TaskCompletionSource<布尔>响应; 
私人字符串_text =;

公共无效的setResult(布尔结果)
{
this.response.SetResult(结果);
}

公共异步任务<布尔> SendYesNo()
{
响应=新TaskCompletionSource<布尔>();

MessageBox.Show(this._text,,MessageBoxButtons.YesNo);

this._text =;

返回response.Task.Result;
}



我使用的是一个JavaScript脚本文件,执行该代码的所以我不能调用的await关键字。



我要返回一个布尔值后,我将它设置的setResult 。如果未设置响应,它会等待,直到它的设置和,直到它的设置不会返回任何东西。它也必须是异步。



如何实现这一点没有任务(因为我不能在JavaScript中使用的await关键字)?


解决方案

如果未设置响应,它会等待,直到它的设置,直到它的设置不会返回任何东西。它也必须是异步




这两个要求是相互的正好相反。



如果您需要等到的结果是可用的,那么你需要它是同步的(这是的定义同步的)。有迹象表明,可以使这项工作的各种黑客 - 调用结果就是其中之一。



如果你需要它是异步的,那么你就不能等到结果可用。在这种情况下,你应该考虑创建一个JavaScript承诺/递延对象,当结果到达通知的对象。


    private TaskCompletionSource<bool> response;
    private string _text = "";

    public void SetResult(bool result)
    {
        this.response.SetResult(result);
    }

    public async Task<bool> SendYesNo()
    {
        response = new TaskCompletionSource<bool>();

        MessageBox.Show(this._text, "", MessageBoxButtons.YesNo);

        this._text = "";

        return response.Task.Result;
    }

I'm using this code which is executed in a JavaScript script file so I can't call the await keyword.

I want to return a boolean after I set it using SetResult. If the response is not set, it will wait until it's set and will not return anything until it's set. It also has to be asychronous.

How to achieve this without Tasks (as I can't use the await keyword in JavaScript)?

解决方案

If the response is not set, it will wait until it's set and will not return anything until it's set. It also has to be asychronous.

Those two requirements are the exact opposite of each other.

If you need to wait until the result is available, then you need it to be synchronous (that's the definition of synchronous). There are various hacks that can make this work - calling Result is one of them.

If you need it to be asynchronous, then you can't wait until the result is available. In that case you should look into creating a JavaScript promise/deferred object and notify that object when the result arrives.

这篇关于C# - 返回一个值异步地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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