pub struct Sender<T> { /* private fields */ }展开描述
向关联的 Receiver 发送一个值。
一对
Sender
和
Receiver
由
channel
函数
创建。
§示例
use tokio::sync::oneshot;
let (tx, rx) = oneshot::channel();
tokio::spawn(async move {
if let Err(_) = tx.send(3) {
println!("the receiver dropped");
}
});
match rx.await {
Ok(v) => println!("got = {:?}", v),
Err(_) => println!("the sender dropped"),
}如果 sender
在
未发送的情况下
被丢弃,
receiver
将
失败并返回
error::RecvError:
use tokio::sync::oneshot;
let (tx, rx) = oneshot::channel::<u32>();
tokio::spawn(async move {
drop(tx);
});
match rx.await {
Ok(_) => panic!("This doesn't happen"),
Err(_) => println!("the sender dropped"),
}要在
析构函数中
使用
Sender,
将其放入
Option
并调用
Option::take。
use tokio::sync::oneshot;
struct SendOnDrop {
sender: Option<oneshot::Sender<&'static str>>,
}
impl Drop for SendOnDrop {
fn drop(&mut self) {
if let Some(sender) = self.sender.take() {
// Using `let _ =` to ignore send errors.
let _ = sender.send("I got dropped!");
}
}
}
let (send, recv) = oneshot::channel();
let send_on_drop = SendOnDrop { sender: Some(send) };
drop(send_on_drop);
assert_eq!(recv.await, Ok("I got dropped!"));实现§
Source§impl<T> Sender<T>
impl<T> Sender<T>
Sourcepub fn send(self, t: T) -> Result<(), T>
pub fn send(self, t: T) -> Result<(), T>
尝试在此通道上发送一个值,如果无法发送则将其返回。
此方法消耗 self,因为 oneshot 通道上只能发送一个值。它未标记为 async,因为向 oneshot 通道发送消息永远不需要任何形式的等待。因此,send 方法可以在同步和异步代码中使用而不会出现问题。
当确定通道的另一端尚未挂起时,发送成功。发送失败的情况是对应的接收者已被释放。请注意,返回 Err 意味着数据将永远不会被接收,但返回 Ok 并不意味着数据一定会被接收。对应的接收者可能在此函数返回 Ok 之后立即挂起。
§示例
向另一个任务发送一个值
use tokio::sync::oneshot;
let (tx, rx) = oneshot::channel();
tokio::spawn(async move {
if let Err(_) = tx.send(3) {
println!("the receiver dropped");
}
});
match rx.await {
Ok(v) => println!("got = {:?}", v),
Err(_) => println!("the sender dropped"),
}Sourcepub async fn closed(&mut self)
pub async fn closed(&mut self)
等待关联的 Receiver 句柄关闭。
Receiver 通过显式调用 close 或丢弃 Receiver 值来关闭。
当与 select! 配对时,此函数用于在接收者不再对结果感兴趣时中止计算。
§Return
返回一个必须被 await 的 Future。
§示例
基本用法
use tokio::sync::oneshot;
let (mut tx, rx) = oneshot::channel::<()>();
tokio::spawn(async move {
drop(rx);
});
tx.closed().await;
println!("the receiver dropped");与 select 配对
use tokio::sync::oneshot;
use tokio::time::{self, Duration};
async fn compute() -> String {
// Complex computation returning a `String`
}
let (mut tx, rx) = oneshot::channel();
tokio::spawn(async move {
tokio::select! {
_ = tx.closed() => {
// The receiver dropped, no need to do any further work
}
value = compute() => {
// The send can fail if the channel was closed at the exact same
// time as when compute() finished, so just ignore the failure.
let _ = tx.send(value);
}
}
});
// Wait for up to 10 seconds
let _ = time::timeout(Duration::from_secs(10), rx).await;Sourcepub fn is_closed(&self) -> bool
pub fn is_closed(&self) -> bool
如果关联的 Receiver 句柄已被丢弃则返回 true。
Receiver 通过显式调用 close 或丢弃 Receiver 值来关闭。
如果返回 true,则对 send 的调用将始终导致错误。
§示例
use tokio::sync::oneshot;
let (tx, rx) = oneshot::channel();
assert!(!tx.is_closed());
drop(rx);
assert!(tx.is_closed());
assert!(tx.send("never received").is_err());Sourcepub fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll<()>
pub fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll<()>
检查 oneshot 通道是否已关闭,如果未关闭,则调度提供的 Context 中的 Waker 在通道关闭时接收通知。
Receiver 通过显式调用 close 或当 Receiver 值被丢弃时来关闭。
请注意,对 poll 的多次调用,只有最近一次调用传递的 Context 中的 Waker 会被调度为接收唤醒。
§Return value
此函数返回:
Poll::Pendingif the channel is still open.Poll::Ready(())if the channel is closed.
§示例
use tokio::sync::oneshot;
use std::future::poll_fn;
let (mut tx, mut rx) = oneshot::channel::<()>();
tokio::spawn(async move {
rx.close();
});
poll_fn(|cx| tx.poll_closed(cx)).await;
println!("the receiver dropped");