Search⌘ K
AI Features

Stop a Task and Async Task

Explore how to stop tasks properly using Task.await, Task.yield, and Task.shutdown in Elixir. Understand when to use each method for task control and how to handle asynchronous task results with async/await to improve concurrent programming.

Stop a task

What happens if our task is stuck and never finishes?

While await/1 stops the task, yield/1 will leave it running. It is good to stop the task manually by calling Task.shutdown(task). The shutdown/1 function also accepts a timeout and gives the process the last chance to complete before stopping it. If it ends, we will receive the result as expected. We can also stop a process immediately by using the :brutal_kill atom as the second argument.

As we can see, using yield/1 and shutdown/1 is a bit more work than await/1. Deciding what to use depends on our use case. A task timeout often ...