c# - appending timeouts to asynchronous requests in WinRT -
i'm using piece of code append timeout request call i'm making ensure don't encounter slow internet connection - , handled appropriately.
when meet timeout condition error message i've been unable fix within extended function.
how go task in general?
code:
public static class soextensions { public static task<t> withtimeout<t>(this task<t> task, timespan duration) { return task.factory.startnew(() => { bool b = task.wait(duration); if (b) return task.result; return default(t); }); } }
usage:
var response = await httpwebrequest .create(request) .getresponseasync() .withtimeout(timespan.fromseconds(1));
i handle aggregateexception
(and through webexception
), still generates aggregateexception
when timeout fails.
i recommend using cancellationtoken
timeouts (new cancellationtokensource(mytimespan).token
), can use within async
methods (e.g., httpclient
, pass token getasync
method). takes fewer resources because http request canceled.
but if want "external" timeout, more natural approach this:
public static async task<t> withtimeout<t>(this task<t> task, timespan duration) { var timeout = task.delay(duration); var completetask = await task.whenany(task, timeout); if (completetask == timeout) return default(t); else return await task; }
this prevent exceptions being wrapped aggregateexception
. it's not efficient cancellationtoken
approach, though, this:
var timeout = new cancellationtokensource(timespan.fromseconds(1)); var response = await new httpclient().getasync(uri, timeout.token);
note cancellationtoken
approach throw operationcanceledexception
instead of returning default(t)
if there timeout.
Comments
Post a Comment