本文介绍了在 F# 中同时等待多个事件的任何事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 F# 中,我知道如何使用 Async 异步等待一个事件.AwaitEvent
:
In F# I know how to wait asynchronously for one event using Async.AwaitEvent
:
let test = async {
let! move = Async.AwaitEvent(form.MouseMove)
...handle move... }
假设我想等待 MouseMove
或 KeyDown
事件.我想要这样的东西:
Suppose I want to wait for either the MouseMove
or the KeyDown
event. I'd like to have something like this:
let! moveOrKeyDown = Async.AwaitEvent(form.MouseMove, form.KeyDown)
此功能不存在,但还有其他方法吗?
This function doesn't exist but is there another way to do this?
推荐答案
let ignoreEvent e = Event.map ignore e
let merged = Event.merge (ignoreEvent f.KeyDown) (ignoreEvent f.MouseMove)
Async.AwaitEvent merged
另一个保留原始类型的版本
another version that preserves original types
let merged = Event.merge (f.KeyDown |> Event.map Choice1Of2) (f.MouseMove |> Event.map Choice2Of2)
Async.AwaitEvent merged
EDIT 2:根据 Tomas Petricek
let e1 = f.KeyDown |> Observable.map Choice1Of2
let e2 = f.MouseMove |> Observable.map Choice2Of2
let! evt = Observable.merge e1 e2 |> Async.AwaitObservable
AwaitObservable 原语可以从这里获取(Tomas Petricek 的Silverlight 中的反应式演示").
AwaitObservable primitive can be taken from here ('Reactive demos in Silverlight' by Tomas Petricek).
这篇关于在 F# 中同时等待多个事件的任何事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!