2

我想在 MonoTouch 应用程序中异步访问 DropBox API。我认为使用本身依赖于RestSharp的DropNet
会很方便。

这两个库都运行良好,但返回 s 的 DropNet 重载Task无法让您将请求与取消令牌相关联。

这是他们的实现的样子:

public Task<IRestResponse> GetThumbnailTask(string path, ThumbnailSize size)
{
    if (!path.StartsWith("/")) path = "/" + path;
    var request = _requestHelper.CreateThumbnailRequest(path, size, Root);
    return ExecuteTask(ApiType.Content, request, cancel);
}

ExecuteTask实现基于TaskCompletionSource最初由 Laurent Kempé编写:

public static class RestClientExtensions
{
    public static Task<TResult> ExecuteTask<TResult>(
        this IRestClient client, IRestRequest request
        ) where TResult : new()
    {
        var tcs = new TaskCompletionSource<TResult>();

        WaitCallback asyncWork = _ => {
            try {
                client.ExecuteAsync<TResult>(request,
                    (response, asynchandle) => {
                        if (response.StatusCode != HttpStatusCode.OK) {
                            tcs.SetException(new DropboxException(response));
                        } else {
                            tcs.SetResult(response.Data);
                        }
                    }
                );
            } catch (Exception exc) {
                    tcs.SetException(exc);
            }
        };

        return ExecuteTask(asyncWork, tcs);
    }


    public static Task<IRestResponse> ExecuteTask(
        this IRestClient client, IRestRequest request
        )
    {
        var tcs = new TaskCompletionSource<IRestResponse>();

        WaitCallback asyncWork = _ => {
            try {
                client.ExecuteAsync(request,
                    (response, asynchandle) => {
                        if (response.StatusCode != HttpStatusCode.OK) {
                            tcs.SetException(new DropboxException(response));
                        } else {
                            tcs.SetResult(response);
                        }
                    }
                );
            } catch (Exception exc) {
                    tcs.SetException(exc);
            }
        };

        return ExecuteTask(asyncWork, tcs);
   }

    private static Task<TResult> ExecuteTask<TResult>(
        WaitCallback asyncWork, TaskCompletionSource<TResult> tcs
        )
    {
        ThreadPool.QueueUserWorkItem(asyncWork);
        return tcs.Task;
    }
}

如何更改或扩展此代码以支持取消CancellationToken
我想这样称呼它:

var task = dropbox.GetThumbnailTask(
    "/test.jpg", ThumbnailSize.ExtraLarge2, _token
);
4

1 回答 1

1

因为CancellationToken是值类型,我们可以将其作为可选参数添加到具有默认值的 API 中,并避免空检查,这很甜蜜。

public Task<IRestResponse> GetThumbnailTask(
    string path, ThumbnailSize size, CancellationToken cancel = default(CancellationToken)
) {
    if (!path.StartsWith("/")) path = "/" + path;
    var request = _requestHelper.CreateThumbnailRequest(path, size, Root);
    return ExecuteTask(ApiType.Content, request, cancel);
}

现在,RestSharpExecuteAsync方法返回RestRequestAsyncHandle封装底层的方法HttpWebRequest以及Abort方法。这就是我们取消事物的方式。

public static Task<TResult> ExecuteTask<TResult>(
    this IRestClient client, IRestRequest request, CancellationToken cancel = default(CancellationToken)
    ) where TResult : new()
{
    var tcs = new TaskCompletionSource<TResult>();
    try {
        var async = client.ExecuteAsync<TResult>(request, (response, _) => {
            if (cancel.IsCancellationRequested || response == null)
                return;

            if (response.StatusCode != HttpStatusCode.OK) {
                tcs.TrySetException(new DropboxException(response));
            } else {
                tcs.TrySetResult(response.Data);
            }
        });

        cancel.Register(() => {
            async.Abort();
            tcs.TrySetCanceled();
        });
    } catch (Exception ex) {
        tcs.TrySetException(ex);
    }

    return tcs.Task;
}

public static Task<IRestResponse> ExecuteTask(this IRestClient client, IRestRequest request, CancellationToken cancel = default(CancellationToken))
{
    var tcs = new TaskCompletionSource<IRestResponse>();
    try {
        var async = client.ExecuteAsync<IRestResponse>(request, (response, _) => {
            if (cancel.IsCancellationRequested || response == null)
                return;

            if (response.StatusCode != HttpStatusCode.OK) {
                tcs.TrySetException(new DropboxException(response));
            } else {
                tcs.TrySetResult(response);
            }
        });

        cancel.Register(() => {
            async.Abort();
            tcs.TrySetCanceled();
        });
    } catch (Exception ex) {
        tcs.TrySetException(ex);
    }

    return tcs.Task;
}

最后,Lauren 的实现将请求放入线程池,但我看不出这样做的理由——<code>ExecuteAsync 本身就是异步的。所以我不这样做。

这就是取消 DropNet 操作。

我还做了一些调整,可能对你有用。

Task因为如果不将调用包装ExecuteTask到另一个s 中,我就无法调度 DropBox s Task,所以我决定为请求找到一个最佳并发级别,结果证明它4适合我,并明确设置它:

static readonly Uri DropboxContentHost = new Uri("https://api-content.dropbox.com");

static DropboxService()
{
    var point = ServicePointManager.FindServicePoint(DropboxContentHost);
    point.ConnectionLimit = 4;
}

我也满足于让未处理的任务异常在地狱中腐烂,所以这就是我所做的:

TaskScheduler.UnobservedTaskException += (sender, e) => {
    e.SetObserved();
};

最后一个观察是您不应该调用Start()返回的任务,DropNet因为该任务会立即开始。如果您不喜欢这样,您将需要包装ExecuteTask另一个不受TaskCompletionSource.

于 2012-11-12T15:52:21.297 回答