ServiceStack “new” api and async await

放肆的年华 提交于 2019-12-05 08:07:51

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.

E.g. the signature for GetAsync is :

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

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");

Unfortunatelly, I had to name the method GetTask for obvious reasons, even though the convention is to append Async to methods that return Task.

With ServiceStack 4, GetAsync now returns a Task, so can can simply use await as expected:

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

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

Note: From what I can tell ServiceStack v4 has many breaking changes from v3.x, and has moved away from BSD licensing with usage limits for their free tier: https://servicestack.net/pricing, so upgrading to 4 may not be an option.

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