繁体   English   中英

ServiceStack“新”api和async等待

[英]ServiceStack “new” api and async await

ServiceStack版本3

我非常熟悉https://github.com/ServiceStack/ServiceStack/wiki/New-API ,在这个页面上它特别说“所有这些API都有异步等价物,你可以在需要时使用它们。”

是否可以使用async等待ServiceStack的新api?

使用异步等待服务器和客户端代码会是什么样的?

[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());

有些人请将这些同步示例转换为异步吗?

文档中提到的“异步”方法不返回Task,因此它们不能与async/await一起使用。 他们实际上需要回调来调用成功或失败。

例如, GetAsync的签名是:

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

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

    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;
    }

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

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

不幸的是,由于显而易见的原因,我不得不将方法命名为GetTask,即使惯例是将Async附加到返回Task方法。

使用ServiceStack 4,GetAsync现在返回一个Task,因此可以按预期使用await:

var client = new JsonServiceClient(BaseUri);
var response = await client.GetAsync(new AllReqstars());

文档: https//github.com/ServiceStack/ServiceStack/wiki/C%23-client#using-the-new-api

注意 :据我所知,ServiceStack v4有很多来自v3.x的重大更改,并且已经放弃了BSD许可,其免费层的使用限制为: https ://servicestack.net/pricing,因此升级到4可能不是一个选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM