Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8815581
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T04:24:55+00:00 2026-06-14T04:24:55+00:00

I want to asynchronously access DropBox API in a MonoTouch app. I thought it

  • 0

I want to asynchronously access DropBox API in a MonoTouch app.
I thought it would be convenient to use DropNet which itself relies on RestSharp.

Both libraries work well but DropNet overloads that return Tasks don’t give you a way to associate requests with cancellation tokens.

This is how their implementation looks:

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 implementation is based on TaskCompletionSource and was originally written by 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;
    }
}

How do I change or extend this code to support cancellation with CancellationToken?
I’d like to call it like this:

var task = dropbox.GetThumbnailTask(
    "/test.jpg", ThumbnailSize.ExtraLarge2, _token
);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T04:24:56+00:00Added an answer on June 14, 2026 at 4:24 am

    Because CancellationToken is a value type, we can add it as an optional parameter to the APIs with default value and avoid null checks, which is sweet.

    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);
    }
    

    Now, RestSharp ExecuteAsync method returns RestRequestAsyncHandle that encapsulates underlying HttpWebRequest, along with Abort method. This is how we cancel things.

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

    Finally, Lauren’s implementation puts requests in thread pool but I don’t see a reason to do so—ExecuteAsync is asynchronous itself. So I don’t do that.

    And that’s it for cancelling DropNet operations.

    I also made a few tweaks which may be useful to you.

    Because I had no way of scheduling DropBox Tasks without resorting to wrapping ExecuteTask calls into another Tasks, I decided to find an optimal concurrency level for requests, which turned out to be 4 for me, and set it explicitly:

    static readonly Uri DropboxContentHost = new Uri("https://api-content.dropbox.com");
    
    static DropboxService()
    {
        var point = ServicePointManager.FindServicePoint(DropboxContentHost);
        point.ConnectionLimit = 4;
    }
    

    I was also content with letting unhandled task exceptions rot in hell, so that’s what I did:

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

    One last observation is you shouldn’t call Start() on a task returned by DropNet because the task starts right away. If you don’t like that, you’ll need to wrap ExecuteTask in yet another “real” task not backed by TaskCompletionSource.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to asynchronously query the Foursquare API, which currently does not allow for
I would like to read asynchronously from stdin with Qt. I don't want to
I want to use jQuery to asynchronously load CSS for a document. I found
I make the application which need internet access. And I want that it will
I have a web form and i want to call Asynchronously Ajax.ActionLink(). Please help
When I want to received UDP datagrams asynchronously, I write call BeginReceiveFrom of a
I'm making a simple reading canvas app, and I want to be ale to
I want to know if it is a good idea to access shared data
I'm trying to use core data in a multi thread way. I simply want
I have this object PreloadClient which implements IDisposable , I want to dispose it,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.