Task<T>
操作:超時和取消>異步編程通常需要等待ATask<T>
完成,但是隨著超時和取消的增加考慮。 這對於用戶體驗至關重要(在一定時間後顯示進度指標或消息)和資源管理(防止不確定的阻塞)。
Task.ContinueWith
>提供異步監視,但缺乏超時功能。 相反,Task.Wait
提供超時處理,但會阻止調用線程。 更優雅的解決方案平衡了兩者的需求。
以下代碼段展示了一種簡潔的方法,以異步等待超時等待任務:
<code class="language-csharp">int timeoutMilliseconds = 1000; var task = SomeOperationAsync(); if (await Task.WhenAny(task, Task.Delay(timeoutMilliseconds)) == task) { // Task completed within the timeout period } else { // Timeout handling – e.g., display a message to the user }</code>
為增強魯棒性,併入取消令牌支持:
<code class="language-csharp">int timeoutMilliseconds = 1000; var cancellationToken = new CancellationTokenSource(); var task = SomeOperationAsync(cancellationToken.Token); try { if (await Task.WhenAny(task, Task.Delay(timeoutMilliseconds, cancellationToken.Token)) == task) { // Task completed within timeout (or was canceled) await task; // Re-await to handle exceptions or cancellation } else { // Timeout or cancellation handling cancellationToken.Cancel(); // Explicit cancellation if needed } } catch (OperationCanceledException) { // Handle cancellation specifically }</code>
塊專門解決try-catch
,允許對取消請求進行量身定制的響應。 在OperationCanceledException
之後重新審議任務可確保正確傳播原始任務中的任何例外或取消信號。 Task.WhenAny
>
以上是我如何異步等待超時和取消任務?的詳細內容。更多資訊請關注PHP中文網其他相關文章!