3

我正在尝试使用 发出异步获取请求ExecuteAsync<T>,但它从不响应。令我困惑的是,ExecuteAsync同步方法ExecuteExecute<T>.

这是我的代码:

var restClient = new RestClient("http://localhost:44268/api/");
var request = new RestRequest("jobs/{id}", Method.GET);
request.AddUrlSegment("id", "194");

// works
var req1 = restClient.Execute(request).Content;

// works
var req2 = restClient.Execute<Job>(request).Content;

// works
var req3 = restClient.ExecuteAsync(request, (restResponse) =>
{
    var test = restResponse.Content;
    Console.WriteLine(test);
});

var req4 = restClient.ExecuteAsync<Job>(request, (restResponse) =>
{
    // this code is never reached
    var test = restResponse.Content;
    Console.WriteLine(test);
});

它成功调用了 API,但它永远不会回调。为什么?难道我做错了什么?

4

4 回答 4

2

ExecuteAsync是异步的。

这意味着对它的调用会立即返回,而无需等待响应。

然后您的程序将照常继续。如果这是一个控制台应用程序并且执行到您的Main方法结束,则整个程序将退出。

所以,你有一个竞争条件。大多数情况下,您的程序将在延续(lambda 回调)有机会运行之前退出。

尝试在方法Console.ReadLine();结束时调用Main以防止提前退出。

于 2012-05-03T18:58:24.830 回答
2

通过升级到最新版本的 RestSharp 解决了这个问题。

于 2012-06-26T14:26:04.093 回答
0
public  Task<IRestResponse> ExecuteAsync<T>(RestRequest request, RestClient client)
{
  EventWaitHandle executedCallBack = new AutoResetEvent(false);
  TaskCompletionSource<IRestResponse> tcs = new TaskCompletionSource<IRestResponse>();

IRestResponse res = new RestResponse();   
    try
    {
      var asyncHandle = client.ExecuteAsync<RestResponse>(request, response =>
        {
          res = response;
          tcs.TrySetResult(res);
          executedCallBack.Set();
        });


    }
    catch (Exception ex)
    {
      tcs.TrySetException(ex);
    }

    return tcs.Task;
}
于 2014-11-20T11:41:14.397 回答
0
IRestResponse loginResponse = new RestResponse();
                    TaskCompletionSource<IRestResponse> tcs = new TaskCompletionSource<IRestResponse>();

//Task task = new Task(() => {client.ExecuteAsync<RestResponse>(request, tcs.SetResult);});// Lambda and anonymous method  
Task task = new Task(() =>client.ExecuteAsync<RestResponse>(request, tcs.SetResult)); // Lambda and named method                    
task.Start();
loginResponse = await tcs.Task;
于 2014-11-21T05:41:44.447 回答