File tree Expand file tree Collapse file tree 2 files changed +23
-3
lines changed Expand file tree Collapse file tree 2 files changed +23
-3
lines changed Original file line number Diff line number Diff line change @@ -23,6 +23,26 @@ use crate::task::{Task, TaskLocalsWrapper};
2323/// # })
2424/// ```
2525pub fn current ( ) -> Task {
26- TaskLocalsWrapper :: get_current ( |t| t. task ( ) . clone ( ) )
27- . expect ( "`task::current()` called outside the context of a task" )
26+ try_current ( ) . expect ( "`task::current()` called outside the context of a task" )
2827}
28+
29+ /// Returns a handle to the current task if called within the context of a task created by [`block_on`],
30+ /// [`spawn`], or [`Builder::spawn`], otherwise returns `None`.
31+ ///
32+ /// [`block_on`]: fn.block_on.html
33+ /// [`spawn`]: fn.spawn.html
34+ /// [`Builder::spawn`]: struct.Builder.html#method.spawn
35+ ///
36+ /// # Examples
37+ ///
38+ /// ```
39+ /// use async_std::task;
40+ ///
41+ /// match task::try_current() {
42+ /// Some(t) => println!("The name of this task is {:?}", t.name()),
43+ /// None => println!("Not inside a task!"),
44+ /// }
45+ /// ```
46+ pub fn try_current ( ) -> Option < Task > {
47+ TaskLocalsWrapper :: get_current ( |t| t. task ( ) . clone ( ) )
48+ }
Original file line number Diff line number Diff line change @@ -133,7 +133,7 @@ cfg_std! {
133133cfg_default ! {
134134 pub use block_on:: block_on;
135135 pub use builder:: Builder ;
136- pub use current:: current;
136+ pub use current:: { current, try_current } ;
137137 pub use task:: Task ;
138138 pub use task_id:: TaskId ;
139139 pub use join_handle:: JoinHandle ;
You can’t perform that action at this time.
0 commit comments