如何在不等待操作员的情况下获得返回值 [英] How to get returned value without await opeartor

查看:66
本文介绍了如何在不等待操作员的情况下获得返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在没有等待操作符的情况下获取返回值(在下面的示例中,我需要在没有等待操作符的情况下在var y中获取"hello world").因为一个方法被引用很多地方,但是我的要求是该方法针对特定操作异步执行.没有其他时间可以同步执行了.

I need to get the returned value without await operator(in below sample I need to get the "hello world" in var y without await operator). Because one method is referred to a lot of places.But my requirement is that method is executed at asynchronously for particular operations. None other time it is enough to be executed as synchronously.

如果我在所有引用的地方都放置等待,则该方法需要更改为异步,并且引用的方法也需要更改为异步并等待. 是否有可能获得返回值?

If I put await in all referred places that method needs to change as async and also referred methods need to change as async and await. Is there any possibility to get the returned value?

请在下面找到示例代码片段:

Please find below sample code snippet:

class Program
{
    static void Main(string[] args)
    {
        var x = getString();
    }

    public static async Task<string> getString()
    {
        var y = await GetString2();
        return y;
    }

    public static async Task<string> GetString2()
    {
        return "hello world";
    }

}

在没有等待操作符的情况下,是否有可能在 var y 中获取"hello world"字符串?

Here is there any possibility to get "hello world" string in var y without await operator?

推荐答案

您是否正在寻找类似的东西;

Are you looking for something like that;

var str = GetString2().Result;

Result阻塞调用线程,直到异步操作完成;否则,该操作不再生效.它等效于Wait方法. await具有异步等待任务完成的功能.

Result blocks the calling thread until the asynchronous operation is complete; it is equivalent the Wait method. await has asynchronous wait for the task completion.

另外,正如@Sir Rufo和@MistyK所描述的那样,您将在可能的异常情况下得到AggregateException,因此像这样使用GetAwaiter会更好;

Also, as @Sir Rufo and @MistyK described, you will get AggregateException on a possible exception, so it would be better to use GetAwaiter like this;

var str = GetString2().GetAwaiter().GetResult();

这篇关于如何在不等待操作员的情况下获得返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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