c# - GetResponseAsync does not accept cancellationToken -


it seems getresponseasync not accept cancellationtoken in async/await. question how can cancel bellow procedure, provided need collect cookies response:

 using (httpwebresponse response = (httpwebresponse) await request.getresponseasync())  {     cookies.add(response.cookies);  } 

an alternative code achieve above welcome.

something should work (untested):

public static class extensions {     public static async task<httpwebresponse> getresponseasync(this httpwebrequest request, cancellationtoken ct)     {         using (ct.register(() => request.abort(), usesynchronizationcontext: false))         {             var response = await request.getresponseasync();             ct.throwifcancellationrequested();             return (httpwebresponse)response;         }     } } 

in theory, if cancellation requested on ct , request.abort invoked, await request.getresponseasync() should throw webexception. imo though, it's idea check cancellation explicitly when consuming result, mitigate race conditions, call ct.throwifcancellationrequested().

also, assume request.abort thread-safe (can called thread), use usesynchronizationcontext: false (i haven't verified that).

[updated] address op's comment on how differentiate between webexception caused cancellation , other error. how can done, taskcanceledexception (derived operationcanceledexception) correctly thrown upon cancellation:

public static class extensions {     public static async task<httpwebresponse> getresponseasync(this httpwebrequest request, cancellationtoken ct)     {         using (ct.register(() => request.abort(), usesynchronizationcontext: false))         {             try             {                 var response = await request.getresponseasync();                 return (httpwebresponse)response;             }             catch (webexception ex)             {                 // webexception thrown when request.abort() called,                 // there may many other reasons,                 // propagate webexception caller correctly                 if (ct.iscancellationrequested)                 {                     // webexception available exception.innerexception                     throw new operationcanceledexception(ex.message, ex, ct);                 }                  // cancellation hasn't been requested, rethrow original webexception                 throw;             }         }     } } 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -