c# - Asynchronously wait for Task<T> to complete with timeout -
i want wait task<t> complete special rules: if hasn't completed after x milliseconds, i want display message user. , if hasn't completed after y milliseconds, i want automatically request cancellation.
i can use task.continuewith asynchronously wait task complete (i.e. schedule action executed when task complete), doesn't allow specify timeout. can use task.wait synchronously wait task complete timeout, blocks thread. how can asynchronously wait task complete timeout?
how this:
int timeout = 1000; var task = someoperationasync(); if (await task.whenany(task, task.delay(timeout)) == task) { // task completed within timeout } else { // timeout logic }
addition: @ request of comment on answer, here expanded solution includes cancellation handling. note passing cancellation task , timer means there multiple ways cancellation can experienced in code, , should sure test , confident handle of them. don't leave chance various combinations , hope computer right thing @ runtime.
int timeout = 1000; var task = someoperationasync(cancellationtoken); if (await task.whenany(task, task.delay(timeout, cancellationtoken)) == task) { // task completed within timeout. // consider task may have faulted or been canceled. // re-await task exceptions/cancellation rethrown. await task; } else { // timeout/cancellation logic }
Comments
Post a Comment