1 | use crate::task::{Task, TaskLocalsWrapper}; |
2 | |
3 | /// Returns a handle to the current task. |
4 | /// |
5 | /// # Panics |
6 | /// |
7 | /// This function will panic if not called within the context of a task created by [`block_on`], |
8 | /// [`spawn`], or [`Builder::spawn`]. |
9 | /// |
10 | /// [`block_on`]: fn.block_on.html |
11 | /// [`spawn`]: fn.spawn.html |
12 | /// [`Builder::spawn`]: struct.Builder.html#method.spawn |
13 | /// |
14 | /// # Examples |
15 | /// |
16 | /// ``` |
17 | /// # async_std::task::block_on(async { |
18 | /// # |
19 | /// use async_std::task; |
20 | /// |
21 | /// println!("The name of this task is {:?}" , task::current().name()); |
22 | /// # |
23 | /// # }) |
24 | /// ``` |
25 | pub fn current() -> Task { |
26 | try_current().expect(msg:"`task::current()` called outside the context of a task" ) |
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: &TaskLocalsWrapper| t.task().clone()) |
48 | } |