【发布时间】:2016-10-03 12:27:49
【问题描述】:
我正在尝试使用 observable.Timeout 设置超时,但结果超出了我的预期。
像这样的代码:
public class ObservableTest : MonoBehaviour {
// Use this for initialization
void Start () {
var subj = new Subject<int> ();
new System.Threading.Thread (() => {
Debug.Log("thread id - " + System.Threading.Thread.CurrentThread.ManagedThreadId);
var i = 0;
while(i < 10) {
i += 1;
System.Threading.Thread.Sleep(i*1000 );
subj.OnNext(i);
}
}).Start();
var timeout = subj.Timeout (System.TimeSpan.FromSeconds (4));
timeout.Subscribe (x => Debug.Log("x - " + x), ex => Debug.LogError(ex), () => Debug.Log("completed"));
}
}
控制台输出:
x - 1
x - 2
...
x - 10
为什么不在x - 5之前中断?如何设置一个observable的超时时间?
更新
x - 8 有时输出中断,我不知道它是如何工作的。
【问题讨论】:
-
嗯。我不知道为什么它继续工作。但是你每走一步都在增加睡眠。所以它应该在 x - 3 处中断
-
@ntohl。我现在知道原因了。如果失去焦点 Unity 编辑器,当你运行时,主线程会挂起......所以代码根本不起作用,但如果你重新关注 Unity,它会再次计算,
x - 8也许当时的活动,此外,发生了超时。