C# 从TaskCompleteSource获取值
从TaskCompleteSource获取数据时遇到问题。我正在向服务器发出一个异步请求,它应该从登录页面返回HTML。这是同步的,但不是异步的 调用client.ExecuteAsync时,是否在尝试从TaskCompleteSource获取数据之前等待响应?我对这里发生的事很困惑C# 从TaskCompleteSource获取值,c#,restsharp,csquery,C#,Restsharp,Csquery,从TaskCompleteSource获取数据时遇到问题。我正在向服务器发出一个异步请求,它应该从登录页面返回HTML。这是同步的,但不是异步的 调用client.ExecuteAsync时,是否在尝试从TaskCompleteSource获取数据之前等待响应?我对这里发生的事很困惑 public Task<bool> login() { var tcs1 = new TaskCompletionSource<CsQuery.CQ>();
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
公共任务登录()
{
var tcs1=新任务完成源();
var tcs2=new TaskCompletionSource();
RestSharp.RestRequest请求;
CsQuery.CQ-dom;
request=new RestSharp.RestRequest(“/accounts/login/”,RestSharp.Method.GET);
client.ExecuteAsync(请求,(异步响应,句柄)=>
{
tcs1.SetResult(asyncResponse.Content);
});
//获取进行登录请求所需的令牌
dom=tcs1.Task.ToString();
//其他代码
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
});
如何将ExecuteAsync与await一起使用以确保它等待?我尝试使用await,但似乎不起作用。您可以执行
tcs1.Task.Wait()
但这将本质上使其同步,并破坏异步调用它的目的。如果有超负荷的ExecuteAsync
返回任务
,并且您正在使用.net 4.5,您可以执行等待ExecuteAsync
。我将修改我的答案,向您展示等待版本。看看这篇文章,它解释了异步编程的一些陷阱
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;
}