跳到主要内容

Sender

搜索

结构体 Sender 

Source
pub struct Sender<T> { /* private fields */ }
展开描述

向关联的 Receiver 发送一个值。

一对 SenderReceiverchannel 函数 创建。

§示例

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>

Source

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"),
}
Source

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;
Source

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());
Source

pub fn poll_closed(&mut self, cx: &mut Context<'_>) -> Poll<()>

检查 oneshot 通道是否已关闭,如果未关闭,则调度提供的 Context 中的 Waker 在通道关闭时接收通知。

Receiver 通过显式调用 close 或当 Receiver 值被丢弃时来关闭。

请注意,对 poll 的多次调用,只有最近一次调用传递的 Context 中的 Waker 会被调度为接收唤醒。

§Return value

此函数返回:

  • Poll::Pending if 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");

Trait 实现§

Source§

impl<T: Debug> Debug for Sender<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

使用给定的格式化器格式化此值。 更多信息
Source§

impl<T> Drop for Sender<T>

Source§

fn drop(&mut self)

执行此类型的析构函数。 更多信息

自动 Trait 实现§

§

impl<T> Freeze for Sender<T>

§

impl<T> !RefUnwindSafe for Sender<T>

§

impl<T> Send for Sender<T>
where T: Send,

§

impl<T> Sync for Sender<T>
where T: Send,

§

impl<T> Unpin for Sender<T>

§

impl<T> UnsafeUnpin for Sender<T>

§

impl<T> !UnwindSafe for Sender<T>

Blanket 实现§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. 更多信息
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. 更多信息
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. 更多信息
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

原样返回传入的参数。

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

调用 U::from(self)

也就是说,此转换的具体行为取决于 From<T> for U 的实现方式。

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

转换出错时返回的类型。
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

执行转换。
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

转换出错时返回的类型。
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

执行转换。