问题描述
通道具有两个功能,可让我们向其中发送事件.Send
和offer
.
Channels have two functions that allow us to send events into it.Send
and offer
.
我想更好地了解两者之间的区别.
I would like to understand better the difference between both.
我有一些想核对的陈述.
I have some statements I wanna check are true.
-
Send
是挂起函数.是什么让我的代码(不是线程)等待它完成.因此,它在send
内部的事件完成/取消后继续运行.还是只有在我可以将事件排队/接收事件之前才会暂停? - 这意味着,如果我从一个通道到另一个通道使用
send
,第一个通道将被阻塞,直到第二个通道可以接收/排队? - 如果我有一个 Rendezvous 频道,并且它已经在运行某些内容(例如,在暂停状态下,正在等待API),并且我
offer
一个新的偶数.这会使offer
引发异常吗?导致频道无法接收?
Send
is a suspend function. What will make my code(not the thread) wait for it to finish. So it keep running after the event insidesend
was complete/cancelled. OR it will be suspend only until I can queue the event/receive it?- This means that, if I use
send
from one channel to another, the first channel will be block until the second can receive/queue? - If I have a Rendezvous Channel and it is already running something (on suspend for example, waiting API) and I
offer
a new even. This will makeoffer
throws exception? Cause the channel is not receiving?
如果您知道任何其他主要区别,我将很高兴知道.
If you know any other main difference I would be glad to know.
预先感谢
推荐答案
send
在发送到的频道已满时,暂停从其调用的协程.
send
suspends the coroutine it is invoked from while the channel being sent to is full.
send
不会从一个通道向另一个通道发送.调用send
时,您正在向该通道发送 元素.然后,该通道期望另一个代码块从其他协程调用receive
.
send
does not send from one channel to another one. When you invoke send
you are sending an element to the channel. The channel then expects another block of code to invoke receive
from a different coroutine.
在RendezvousChannel
中,容量为0
.这意味着send
总是挂起,等待来自另一个协程的receive
调用.如果您已在RendezvousChannel
上调用send
,然后使用offer
,则 offer
不会引发异常(仅在关闭通道的情况下会发生),但是如果没有平衡,它将返回false
初始send
之后,已在RendezvousChannel
上调用了receive
.这是因为offer
会尝试在不违反其容量限制的情况下立即将元素添加到通道中.
In a RendezvousChannel
the capacity is 0
. This means that send
always suspends waiting for a receive
invocation from another coroutine. If you have invoked send
on a RendezvousChannel
and then use offer
, offer
will not throw an exception (it only does if the channel is closed), but rather it will return false
if no balancing receive
has been invoked on the RendezvousChannel
after your initial send
. This is because offer
tries to immediately add the element to the channel if it doesn't violate its capacity restrictions.
这篇关于Kotlin Channels发送和提供之间的用法差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!