[][src]Struct smol::Task

#[must_use =
  "tasks get canceled when dropped, use `.detach()` to run them in the background"]pub struct Task<T>(_);

A spawned future.

Tasks are also futures themselves and yield the output of the spawned future.

When a task is dropped, its gets canceled and won't be polled again. To cancel a task a bit more gracefully and wait until it stops running, use the cancel() method.

Tasks that panic get immediately canceled. Awaiting a canceled task also causes a panic.

If the future panics, the panic will be unwound into the run() invocation that polled it. However, this does not apply to the blocking executor - it will simply ignore panics and continue running.

Examples

use smol::Task;

// Spawn a task onto the work-stealing executor.
let task = Task::spawn(async {
    println!("Hello from a task!");
    1 + 2
});

// Wait for the task to complete.
assert_eq!(task.await, 3);

Implementations

impl<T: 'static> Task<T>[src]

pub fn local(future: impl Future<Output = T> + 'static) -> Task<T>[src]

Spawns a future onto the thread-local executor.

Panics if the current thread is not inside an invocation of run().

Examples

use smol::Task;

let task = Task::local(async { 1 + 2 });
assert_eq!(task.await, 3);

impl<T: Send + 'static> Task<T>[src]

pub fn spawn(future: impl Future<Output = T> + Send + 'static) -> Task<T>[src]

Spawns a future onto the work-stealing executor.

This future may be stolen and polled by any thread calling run().

Examples

use smol::Task;

let task = Task::spawn(async { 1 + 2 });
assert_eq!(task.await, 3);

pub fn blocking(future: impl Future<Output = T> + Send + 'static) -> Task<T>[src]

Spawns a future onto the blocking executor.

This future is allowed to block for an indefinite length of time.

For convenience, there is also the blocking! macro that spawns a blocking tasks and immediately awaits it.

Examples

Read a line from the standard input:

use smol::Task;
use std::io::stdin;

let line = Task::blocking(async {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    line
})
.await;

See also examples for blocking!, iter(), reader(), and writer().

impl<T, E> Task<Result<T, E>> where
    T: Send + 'static,
    E: Debug + Send + 'static, 
[src]

pub fn unwrap(self) -> Task<T>[src]

Spawns a new task that awaits and unwraps the result.

The new task will panic if the original task results in an error.

Examples

use smol::{Async, Task};
use std::net::TcpStream;

let stream = Task::spawn(async {
    Async::<TcpStream>::connect("example.com:80").await
})
.unwrap()
.await;

pub fn expect(self, msg: &str) -> Task<T>[src]

Spawns a new task that awaits and unwraps the result.

The new task will panic with the provided message if the original task results in an error.

Examples

use smol::{Async, Task};
use std::net::TcpStream;

let stream = Task::spawn(async {
    Async::<TcpStream>::connect("example.com:80").await
})
.expect("cannot connect")
.await;

impl Task<()>[src]

pub fn detach(self)[src]

Detaches the task to let it keep running in the background.

Examples

use smol::{Task, Timer};
use std::time::Duration;

Task::spawn(async {
    loop {
        println!("I'm a daemon task looping forever.");
        Timer::after(Duration::from_secs(1)).await;
    }
})
.detach();

impl<T> Task<T>[src]

pub async fn cancel(self) -> Option<T>[src]

Cancels the task and waits for it to stop running.

Returns the task's output if it was completed just before it got canceled, or None if it didn't complete.

While it's possible to simply drop the Task to cancel it, this is a cleaner way of canceling because it also waits for the task to stop running.

Examples

use smol::{Task, Timer};
use std::time::Duration;

let task = Task::spawn(async {
    loop {
        println!("Even though I'm in an infinite loop, you can still cancel me!");
        Timer::after(Duration::from_secs(1)).await;
    }
});

Timer::after(Duration::from_secs(3)).await;
task.cancel().await;

Trait Implementations

impl<T> Debug for Task<T>[src]

impl<T> Drop for Task<T>[src]

impl<T> Future for Task<T>[src]

type Output = T

The type of value produced on completion.

impl<T> Into<JoinHandle<T, ()>> for Task<T>[src]

Auto Trait Implementations

impl<T> !RefUnwindSafe for Task<T>

impl<T> Send for Task<T> where
    T: Send

impl<T> !Sync for Task<T>

impl<T> Unpin for Task<T>

impl<T> !UnwindSafe for Task<T>

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T> FutureExt for T where
    T: Future + ?Sized
[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<F, T, E> TryFuture for F where
    F: Future<Output = Result<T, E>> + ?Sized
[src]

type Ok = T

The type of successful values yielded by this future

type Error = E

The type of failures yielded by this future

impl<Fut> TryFutureExt for Fut where
    Fut: TryFuture + ?Sized
[src]

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.