Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Async Timeout Handling | Timeouts, Parallelism, and Error Handling
C# Async and Await Practice

bookChallenge: Async Timeout Handling

Opgave

Swipe to start coding

Implement an async timeout handler using Task.WhenAny and CancellationToken. You will create an async method that runs a simulated long-running operation for a specified duration, but cancels it if it takes longer than a specified timeout.

  • The LongRunningOperationAsync method must simulate a long-running operation using Task.Delay, accept the operation duration in milliseconds, and accept a CancellationToken to support cancellation.
  • The RunWithTimeoutAsync method must start the long-running operation (with a configurable duration) and a timeout task, then use Task.WhenAny to determine which completes first.
  • If the long-running operation completes before the timeout, return its result.
  • If the timeout occurs before the operation completes, cancel the operation and return "Operation Timed Out".
  • Both operation duration and timeout must be parameters to allow for flexible testing.

Løsning

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 2
single

single

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

close

bookChallenge: Async Timeout Handling

Stryg for at vise menuen

Opgave

Swipe to start coding

Implement an async timeout handler using Task.WhenAny and CancellationToken. You will create an async method that runs a simulated long-running operation for a specified duration, but cancels it if it takes longer than a specified timeout.

  • The LongRunningOperationAsync method must simulate a long-running operation using Task.Delay, accept the operation duration in milliseconds, and accept a CancellationToken to support cancellation.
  • The RunWithTimeoutAsync method must start the long-running operation (with a configurable duration) and a timeout task, then use Task.WhenAny to determine which completes first.
  • If the long-running operation completes before the timeout, return its result.
  • If the timeout occurs before the operation completes, cancel the operation and return "Operation Timed Out".
  • Both operation duration and timeout must be parameters to allow for flexible testing.

Løsning

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 2
single

single

some-alt