@@ -23,6 +23,26 @@ use crate::task::{Task, TaskLocalsWrapper};
23
23
/// # })
24
24
/// ```
25
25
pub 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" )
28
27
}
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
+ }
0 commit comments