我在从TaskCompleteSource获取数据时遇到一些麻烦。我正在向服务器发出异步请求,它应该从登录页面返回HTML。这可以同步,但不是Asyn。
调用client.ExecuteAsync是否在尝试从TaskCompleteSource获取数据之前等待响应?我对这里发生的事情感到很困惑。
public Task<bool> login()
{
var tcs1 = new TaskCompletionSource<CsQuery.CQ>();
var tcs2 = new TaskCompletionSource<bool>();
RestSharp.RestRequest request;
CsQuery.CQ dom;
request = new RestSharp.RestRequest("/accounts/login/", RestSharp.Method.GET);
client.ExecuteAsync(request, (asyncResponse, handle) =>
{
tcs1.SetResult(asyncResponse.Content);
});
// Get the token needed to make the login request
dom = tcs1.Task.ToString();
// Other Code
答案 0 :(得分:0)
ExecuteAsync
方法会立即返回,如果您想处理设置任务延续所需的响应。
var tcs1 = new TaskCompletionSource<CsQuery.CQ>();
var tcs2 = new TaskCompletionSource<bool>();
RestSharp.RestRequest request;
CsQuery.CQ dom;
request = new RestSharp.RestRequest("/accounts/login/", RestSharp.Method.GET);
client.ExecuteAsync(request, (asyncResponse, handle) =>
{
tcs1.SetResult(asyncResponse.Content);
});
tcs1.Task.ContinueWith( () =>
{
// Get the token needed to make the login request
dom = tcs1.Task.ToString();
// Other Code
});
如果您使用的是.NET 4.5,还可以使用新的async / await语法。我已将TaskCompletionSource
的类型修改为string
,因为我无法访问CsQuery.CQ
类型。
public async Task<bool> login()
{
var tcs1 = new TaskCompletionSource<string>();
RestSharp.RestRequest request;
request = new RestSharp.RestRequest("/accounts/login/", RestSharp.Method.GET);
client.ExecuteAsync(request, (asyncResponse, handle) =>
{
tcs1.SetResult(asyncResponse.Content);
});
await tcs1.Task;
// Other Code ...
return true;
}