How to cancel a synchronized call to RestSharp?

I have this line that makes a blocking (synchronous) web service call and works great:

var response = client.Execute<DataRequestResponse>(request);

( varrepresents IRestResponse<DataRequestResponse>)

But now I want to be able to cancel it (from another thread). (I found this similar question , but my code should remain synchronized - code changes should remain localized in this function.)

I found CancellationTokenSourceand a ExecuteTaskAsync()that accepts CancellationToken. (See https://stackoverflow.com/a/166269/ ) It seems like this can do the job. I got to this code:

var cancellationTokenSource = new CancellationTokenSource();
var task = client.ExecuteTaskAsync(request, cancellationTokenSource.Token);
task.Wait();
var response = task.Result;

The last line refuses to compile, telling me that it cannot perform an implicit translation. So I tried an explicit cast:

IRestResponse<DataRequestResponse> response = task.Result as IRestResponse<DataRequestResponse>;

, , ( NullReferenceException, : " ​​ " ).

(, , cancellationTokenSource.Token, , , , , : .)

- , . , . "", .

:

sync Execute : https://github.com/restsharp/RestSharp/blob/master/RestSharp/RestClient.Sync.cs#L55, Http.AsGet() Http.AsPost(), : https://github.com/restsharp/RestSharp/blob/master/RestSharp/Http.Sync.cs#L194

, RestSharp HttpWebRequest.GetResponse. Abort, (.. , ), !

+4
2

var response = client.Execute<DataRequestResponse>(request);

- public virtual Task<IRestResponse<T>> ExecuteTaskAsync<T>(IRestRequest request, CancellationToken token) RestSharp.

. () , :

var cancellationTokenSource = new CancellationTokenSource();

// ...

var task = client.ExecuteTaskAsync<DataRequestResponse>(
    request,    
    cancellationTokenSource.Token);

// this will wait for completion and throw on cancellation.
var response = task.Result; 
+4

:

var response = client.Execute<MyData>(request);
process(response);

:

var response = null;
EventWaitHandle handle = new AutoResetEvent (false);
client.ExecuteAsync<MyData>(request, r => {
    response = r;
    handle.Set();
    });
handle.WaitOne();
process(response);

, . :

bool volatile cancelAllRequests = false;
...
var response = null;
EventWaitHandle handle = new AutoResetEvent (false);
RestRequestAsyncHandle asyncRequest = client.ExecuteAsync<MyData>(request, r => {
     response = r;
     handle.Set();
     });
 while(true){            
     if(handle.WaitOne(250))break;   //Returns true if async operation finished
     if(cancelAllRequests){
         asyncRequest.WebRequest.Abort();
         return;
         }
     }
process(response);

(, , , , ​​...)

0

All Articles