ServiceStack"新" API和异步等待 [英] ServiceStack "new" api and async await

查看:149
本文介绍了ServiceStack"新" API和异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ServiceStack版本3

我很熟悉 https://github.com/ServiceStack/ServiceStack/维基/新的API ,并在此页面上它明确表示,所有这些API都异步等价物,你可以改用,当您需要。

I'm quite familiar with https://github.com/ServiceStack/ServiceStack/wiki/New-API and on this page it specifically says "All these APIs have async equivalents which you can use instead, when you need to."

是否有可能使用异步等待着ServiceStack新的API?

Is it possible to use async await with ServiceStack's new api?

会是什么样的服务器和客户端code看起来像异步等待?

What would the server and client code look like with async await?

[Route("/reqstars")]
public class AllReqstars : IReturn<List<Reqstar>> { }

public class ReqstarsService : Service
{
    public List<Reqstar> Any(AllReqstars request) 
    {
        return Db.Select<Reqstar>();
    }
}

客户端

var client = new JsonServiceClient(BaseUri);
List<Reqstar> response = client.Get(new AllReqstars());

会请一些转换这些同步例子异步的?

Would some please convert these synchronous examples to asynchronous?

推荐答案

的文档不返回任务中提到,使他们无法与中的异步的方法异步/的await ,因为它们。他们实际上需要回调的成功或失败呼叫。

The "async" methods mentioned in the documentation do not return Task so they can't be used with async/await as they are. They actually require callbacks to call on success or failure.

例如。为 GetAsync 的签名是:

public virtual void GetAsync<TResponse>(string relativeOrAbsoluteUrl, 
    Action<TResponse> onSuccess, 
    Action<TResponse, Exception> onError)

这是异步函数的APM风格,可以使用TaskCompletionSource,转换为基于任务的功能,例如:

This is the APM-style of asynchronous functions and can be converted to Task-based functions using a TaskCompletionSource, eg:

    public static Task<TResponse> GetTask<TResponse>(this JsonServiceClient client, string url)
    {
        var tcs = new TaskCompletionSource<TResponse>();

        client.GetAsync<TResponse>(url,
            response=>tcs.SetResult(response),
            (response,exc)=>tcs.SetException(exc)
            );

        return tcs.Task;
    }

您可以调用像这样的扩展方法:

You can call the extension method like this:

var result = await client.GetTask<SomeClass>("someurl");

可惜的是,我不得不说出原因很明显的方法GetTask,即使约定是异步追加到返回的方法任务

这篇关于ServiceStack&QUOT;新&QUOT; API和异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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