2

我正在使用 ServiceStack 对 Web 服务 API 进行原型设计,并且在测试 GetAsync 时遇到了问题。具体来说,onSuccess 操作不会在我期望的时候被调用。

这是我的代码:

服务器:

[Route("/accounts/", "GET")
public class AccountRequest : IReturn<AccountResponse>
{
    public string EmailAddress {get; set;}
}

public class AccountResponse
{
    public Account Account {get; set;}
}

public class AccountService : Service
{
    public object Get(AccountRequest request)
    {
        return new AccountResponse{Account = new Account.....
    }
}

非常基本,几乎与ServiceStack.net上的 hello world 示例一样

和有问题的客户端 GetAsync 调用:

using(var client = new JsonServiceClient("some url")
{
    client.GetAsync(new AccountRequest{EmailAddress = "gibbons"},
            response => Console.WriteLine(response.Account.Something), //This never happens
            (response, ex) => {throw ex;}); // if it matters, neither does this

}

然而,这完全符合预期......

using(var client = new JsonServiceClient("some url")
{
    var acc = client.Get(new AccountRequest{EmailAddress = "gibbons"});

    //acc is exactly as expected.
}

有趣的是,一个接一个地测试异步和非异步也可以:

using(var client = new JsonServiceClient("some url")
{
     client.GetAsync(new AccountRequest{EmailAddress = "gibbons"},
                    response => Console.WriteLine(response.Account.Something), //Works
                    (response, ex) => {throw ex;});

    var acc = client.Get(new AccountRequest{EmailAddress = "gibbons"});

    //Again, acc is exactly as expected.
}

在所有情况下,我都可以看到通过 Fiddler 通过 HTTP 传输的实际数据,所以我认为我缺少对异步 api 工作原理的一些基本了解。

欢迎任何帮助。谢谢。

4

1 回答 1

1

阻塞同步 API 在响应完成之前不会返回,因为异步 API 是非阻塞的,因此执行会立即继续。只有在返回和处理响应时才会触发回调。

AsyncRestClientTests.cs测试中,它会休眠 1 秒,Thread.Sleep(1000)然后断言及时返回了响应。

您要等待多长时间才能确定回调是否被触发?

于 2012-12-28T02:45:30.457 回答