Skip to content

add task::try_current #951

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions src/task/current.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,26 @@ use crate::task::{Task, TaskLocalsWrapper};
/// # })
/// ```
pub fn current() -> Task {
TaskLocalsWrapper::get_current(|t| t.task().clone())
.expect("`task::current()` called outside the context of a task")
try_current().expect("`task::current()` called outside the context of a task")
}

/// Returns a handle to the current task if called within the context of a task created by [`block_on`],
/// [`spawn`], or [`Builder::spawn`], otherwise returns `None`.
///
/// [`block_on`]: fn.block_on.html
/// [`spawn`]: fn.spawn.html
/// [`Builder::spawn`]: struct.Builder.html#method.spawn
///
/// # Examples
///
/// ```
/// use async_std::task;
///
/// match task::try_current() {
/// Some(t) => println!("The name of this task is {:?}", t.name()),
/// None => println!("Not inside a task!"),
/// }
/// ```
pub fn try_current() -> Option<Task> {
TaskLocalsWrapper::get_current(|t| t.task().clone())
}
2 changes: 1 addition & 1 deletion src/task/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ cfg_std! {
cfg_default! {
pub use block_on::block_on;
pub use builder::Builder;
pub use current::current;
pub use current::{current, try_current};
pub use task::Task;
pub use task_id::TaskId;
pub use join_handle::JoinHandle;
Expand Down