ServiceStack“新”api和async等待

ServiceStack版本3

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

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

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

[Route("/reqstars")] public class AllReqstars : IReturn<List> { } public class ReqstarsService : Service { public List Any(AllReqstars request) { return Db.Select(); } } 

客户

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

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

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

例如, GetAsync的签名是:

 public virtual void GetAsync(string relativeOrAbsoluteUrl, Action onSuccess, Action onError) 

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

  public static Task GetTask(this JsonServiceClient client, string url) { var tcs = new TaskCompletionSource(); client.GetAsync(url, response=>tcs.SetResult(response), (response,exc)=>tcs.SetException(exc) ); return tcs.Task; } 

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

 var result = await client.GetTask("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可能不是一个选项。