Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d395607

Browse files
Merge pull request #951 from mglagla/try-current
add task::try_current
2 parents 4d9499c + 7fecd0d commit d395607

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

‎src/task/current.rs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,26 @@ use crate::task::{Task, TaskLocalsWrapper};
2323
/// # })
2424
/// ```
2525
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")
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+
}

‎src/task/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ cfg_std! {
133133
cfg_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;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /