从TaskCompletionSource获取价值

时间:2013-08-11 09:48:07

标签: c# restsharp csquery

我在从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

1 个答案:

答案 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;
}