[英]Thread-safe raising of F# events
I'm trying to do an F# async computation that calls an C# callback when ready. 我正在尝试进行F#异步计算,在准备就绪时调用C#回调。 The code is the following:
代码如下:
type Worker() =
let locker = obj()
let computedValue = ref None
let started = ref false
let completed = Event<_>()
let doNothing() = ()
member x.Compute(callBack:Action<_>) =
let workAlreadyStarted, action =
lock locker (fun () ->
match !computedValue with
| Some value ->
true, (fun () -> callBack.Invoke value)
| None ->
completed.Publish.Add callBack.Invoke
if !started then
true, doNothing
else
started := true
false, doNothing)
action()
if not workAlreadyStartedthen
async {
// heavy computation to calc result
let result = "result"
lock locker (fun () ->
computedValue := Some result
completed.Trigger result)
} |> Async.Start
But there's a problem, I want to trigger the completed event outside the lock, but I want to make sure that the triggering is thread safe (Actually, in this small example I could just trigger the event outside the lock as I know no one else will subscribe to it, but that's not always the case). 但是有一个问题,我想在锁定之外触发已完成的事件,但是我想确保触发是线程安全的(实际上,在这个小例子中我可以触发锁外的事件,因为我不知道其他人会订阅它,但情况并非总是如此)。
In C# events this is very easy to accomplish: 在C#事件中,这很容易实现:
object locker = new object();
event Action<string> MyEvent;
void Raise()
{
Action<string> myEventCache;
lock (locker)
{
myEventCache = MyEvent;
}
if (myEventCache != null)
{
myEventCache("result");
}
}
How can I do the equivalent with F# events, freezing the list of subscribers inside the lock but invoking it outside the lock? 如何使用F#事件执行等效操作,冻结锁内的订户列表,但在锁外调用它?
This isn't as straightforward in F# because Event<_>
doesn't expose its subscriber list, which is mutated by Add
/ Remove
. 这在F#中并不那么简单,因为
Event<_>
不公开其订阅者列表,该列表由Add
/ Remove
突变。
You can avoid this mutation by creating a new event for each handler. 您可以通过为每个处理程序创建新事件来避免此突变。
let mutable completed = Event<_>()
//...
let ev = Event<_>()
let iev = ev.Publish
iev.Add(completed.Trigger)
iev.Add(callBack.Invoke)
completed <- ev
//...
let ev = lock locker <| fun () ->
computedValue := Some result
completed
ev.Trigger(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.