C# - Return a value asychronously

一曲冷凌霜 提交于 2019-12-20 07:16:37

问题


    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)?


回答1:


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.



来源:https://stackoverflow.com/questions/30899053/c-sharp-return-a-value-asychronously

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