byref引用参考单元格的值

时间:2015-03-31 14:37:41

标签: syntax f#

我偶然发现了这个问题。我需要一个能知道它被调用多少次的函数。它需要是线程安全的,所以我想使用Interlocked.Increment来增加计数器(没有锁,因为在这种情况下,锁会消除与多线程相关的所有性能增益)。 无论如何,问题是语法问题:如何在引用单元格中引用值(&!counter)?

let functionWithSharedCounter = 
    let counter = ref 0
    fun () ->
        // I tried the ones below:
        // let index = Interlocked.Increment(&counter)
        // let index = Interlocked.Increment(&!counter)
        // let index = Interlocked.Increment(&counter.Value)
        printfn "captured value: %d" index

functionWithSharedCounter ()
functionWithSharedCounter ()
functionWithSharedCounter ()

干杯,

1 个答案:

答案 0 :(得分:2)

F#会自动将ref类型的值视为byref参数,因此您不需要任何特殊语法:

let functionWithSharedCounter = 
    let counter = ref 0
    fun () ->
        let index = Interlocked.Increment(counter)
        printfn "captured value: %d" index

您也可以参考可变字段,因此您也可以编写以下内容:

let index = Interlocked.Increment(&counter.contents)

这适用于归档contents,但不适用于counter.Value,因为这是属性。

相关问题