Skip to content

Commit

Permalink
fixed multi-threading issue in PrimitiveValueConverter
Browse files Browse the repository at this point in the history
  • Loading branch information
luithefirst committed May 28, 2024
1 parent ef0679d commit 056b3f6
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions src/Aardvark.Rendering/Resources/Adaptive/AdaptiveConverter.fs
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,22 @@ module AdaptivePrimitiveValueConverterExtensions =
member x.ConvertUntyped(value : IAdaptiveValue) = x.Convert(value)
member x.Convert(array : aval<Array>) = x.Convert(array)

let private staticFieldCache = Dict<Type * string, obj>()
let private getStaticField (name : string) (t : Type) : 'T =
staticFieldCache.GetOrCreate((t, name), fun (t, name) ->
let p = t.GetProperty(name, BindingFlags.Static ||| BindingFlags.NonPublic ||| BindingFlags.Public)
p.GetValue(null)
) |> unbox<'T>
let private staticInstanceCache = Dict<Type, obj>()
let private getStaticInstance (t : Type) : 'T =
lock staticInstanceCache (fun () ->
staticInstanceCache.GetOrCreate(t, fun t ->
let p = t.GetProperty("Instance", BindingFlags.Static ||| BindingFlags.NonPublic ||| BindingFlags.Public)
p.GetValue(null)
) |> unbox<'T>
)

let convertArray (inputElementType : Type) (array : aval<Array>) : aval<'T[]> =
if inputElementType = typeof<'T> then
array |> AdaptiveResource.mapNonAdaptive unbox
else
try
let tconv = typedefof<AdaptiveConverter<_,_>>.MakeGenericType [| inputElementType; typeof<'T> |]
let converter : IAdaptiveConverter<'T> = tconv |> getStaticField "Instance"
let converter : IAdaptiveConverter<'T> = tconv |> getStaticInstance
converter.Convert(array)
with
| InvalidConversion exn -> raise exn
Expand All @@ -70,7 +72,7 @@ module AdaptivePrimitiveValueConverterExtensions =
else
try
let tconv = typedefof<AdaptiveConverter<_,_>>.MakeGenericType [| inputType; outputType |]
let converter : IAdaptiveConverter = tconv |> getStaticField "Instance"
let converter : IAdaptiveConverter = tconv |> getStaticInstance
converter.ConvertUntyped(value)
with
| InvalidConversion exn -> raise exn
Expand All @@ -82,7 +84,7 @@ module AdaptivePrimitiveValueConverterExtensions =
else
try
let tconv = typedefof<AdaptiveConverter<_,_>>.MakeGenericType [| inputType; typeof<'T> |]
let converter : IAdaptiveConverter<'T> = tconv |> getStaticField "Instance"
let converter : IAdaptiveConverter<'T> = tconv |> getStaticInstance
converter.Convert(value)
with
| InvalidConversion exn -> raise exn

0 comments on commit 056b3f6

Please sign in to comment.