KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have a .NET (C#) application that makes extensive use of async/await. I feel like I've got my head around async/await, but I'm trying to use a library (RestSharp) that has an older (or perhaps I should just say different) programming model that uses callbacks for asynchronous operations. RestSharp's RestClient class has an ExecuteAsync method that takes a callback parameter, and I wanted to be able to put a wrapper around that which would allow me to await the whole operation. The ExecuteAsync method looks something like this: public RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action<IRestResponse> callback); I thought I had it all working nicely. I used TaskCompletionSource to wrap the ExecuteAsync call in something that I could await, as follows: public static async Task<T> ExecuteRequestAsync<T>(RestRequest request, CancellationToken cancellationToken) where T : new() { var response = await ExecuteTaskAsync(request, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(response.Content); } private static async Task<IRestResponse> ExecuteTaskAsync(RestRequest request, CancellationToken cancellationToken) { var taskCompletionSource = new TaskCompletionSource<IRestResponse>(); var asyncHandle = _restClient.ExecuteAsync(request, r => { taskCompletionSource.SetResult(r); }); cancellationToken.Register(() => asyncHandle.Abort()); return await taskCompletionSource.Task; } This has been working fine for most of my application. However, I have one part of the application that does hundreds of calls to my ExecuteRequestAsync as part of a single operation, and that operation shows a progress dialog with a cancel button. You'll see th
Tags (comma-separated)
Save Edits
Cancel