Note that there are some explanatory texts on larger screens.

plurals
  1. POThread-safe raising of F# events
    primarykey
    data
    text
    <p>I'm trying to do an F# async computation that calls an C# callback when ready. The code is the following:</p> <pre><code>type Worker() = let locker = obj() let computedValue = ref None let started = ref false let completed = Event&lt;_&gt;() let doNothing() = () member x.Compute(callBack:Action&lt;_&gt;) = let workAlreadyStarted, action = lock locker (fun () -&gt; match !computedValue with | Some value -&gt; true, (fun () -&gt; callBack.Invoke value) | None -&gt; 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 () -&gt; computedValue := Some result completed.Trigger result) } |&gt; Async.Start </code></pre> <p>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).</p> <p>In C# events this is very easy to accomplish:</p> <pre><code> object locker = new object(); event Action&lt;string&gt; MyEvent; void Raise() { Action&lt;string&gt; myEventCache; lock (locker) { myEventCache = MyEvent; } if (myEventCache != null) { myEventCache("result"); } } </code></pre> <p>How can I do the equivalent with F# events, freezing the list of subscribers inside the lock but invoking it outside the lock?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload