0

我在从 TaskCompleteSource 获取数据时遇到了一些麻烦。我正在向服务器发出异步请求,它应该从登录页面返回 HTML。这工作同步,但不是异步。

调用 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
4

1 回答 1

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为 astring因为我无权访问该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;
} 
于 2013-08-11T10:24:53.430 回答