我正在尝试使用ExecuteAsync<T>
制作异步获取请求,但它从不响应。让我感到困惑的是,ExecuteAsync
和Execute
以及Execute<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,但它永远不会回调。为什么?我做错了吗?
答案 0 :(得分:2)
ExecuteAsync
是异步的。
这意味着对它的调用立即返回而不等待响应。
然后你的程序正常继续。如果这是一个控制台应用程序并且执行到了Main
方法的末尾,则整个程序将退出。
所以,你有一个竞争条件。大多数情况下,程序将在continuation(lambda回调)有机会运行之前退出。
尝试在Console.ReadLine();
方法的末尾发出Main
来电,以防止提前退出。
答案 1 :(得分:1)
通过升级到最新版本的RestSharp解决了这个问题。
答案 2 :(得分: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;
}
答案 3 :(得分: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;