将TPL与现有异步API一起使用

Cla*_*sen 8 c# task-parallel-library restsharp

我想将TPL与现有的API一起使用,RestSharp是特定的,所以我可以使用continuation.

但这意味着我必须将一个不采用传统.NET方法的API包装成异步,而是实现回调.拿这样的代码:

var client = new RestClient("service-url");
var request = new RestRequest();

client.ExecuteAsync<List<LiveTileWeatherResponse>>(request, 
    (response) =>
    {
        ...
    });
Run Code Online (Sandbox Code Playgroud)

所以我想在TPL中包装ExecuteAsync,如果可能的话.但我不能为我的生活,弄清楚如何做到这一点.

有任何想法吗?

Boj*_*nik 12

TPL提供了TaskCompletionSource类,它允许您将任何内容公开为任务.通过调用SetResultSetException,可以使任务成功或失败.在您的示例中,您可能会执行以下操作:

static Task<T> ExecuteTask<T>(this RestClient client, RestRequest request)
{
    var tcs = new TaskCompletionSource<T>();
    client.ExecuteAsync<T>(request, response => tcs.SetResult(response));
    return tcs.Task;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它:

var task = client.ExecuteTask<List<LiveTileWeatherResponse>>(request);
foreach (var tile in task.Result)
{}
Run Code Online (Sandbox Code Playgroud)

或者,如果您想链接任务:

var task = client.ExecuteTask<List<LiveTileWeatherResponse>>(request);
task.ContinueWith(
    t => 
    {
        foreach (var tile in t.Result)
        {}
    }
);
Run Code Online (Sandbox Code Playgroud)

您可以在http://blogs.msdn.com/b/pfxteam/archive/2009/06/02/9685804.aspx上阅读有关TaskCompletionSource的更多信息.