Search Unity

I wrote a code comment today

Discussion in 'General Discussion' started by AndersMalmgren, Aug 29, 2019.

  1. Glader

    Glader

    Joined:
    Aug 19, 2013
    Posts:
    456
    Yes MemoryCache uses ConcurrentDictionary so it's threadsafe. Unfortunately though, I still think this will definitely hurt throughput contending a semaphore for this IF you access the cache often with this get or create approach.

    My perferred approach in this scenario would be an AsyncReaderWriterLock in upgradable read mode so in best case scenario it exists, you don't have any contention reading the cache in multiple threads and if it doesn't exist you can upgrade to a write lock from there. Especially since this is locking for all keys and not just this one key value I am hopeful this is not in a hot path ^,^

    Also MemoryCache is not a sealed type and you could re-rewrite the extension method for GetOrCreate to utilize a derived MemoryCache type's synchronization object. Using this as a guidance ^,^ https://github.com/aspnet/Caching/b...ng.Abstractions/MemoryCacheExtensions.cs#L108
     
  2. Glader

    Glader

    Joined:
    Aug 19, 2013
    Posts:
    456
    Also, a word of warning to anyone using async/await in Unity3D. If you're doing it from within the context of the main thread and not using ConfigureAwait(false) you will end up running with Unity's internal synchronization context which, if I recall correctly, is only serviced every fixed update. This can add some significant latency to the continuation of tasks which some applications of async code may be dramatically affect by such as a realtime networking.

    Of course sometimes you want to continue on the main thread so it's ok but in many cases it can be the cause of some latency for the completion of async operations.
     
  3. iamthwee

    iamthwee

    Joined:
    Nov 27, 2015
    Posts:
    2,149
    Nice, I'm closer to figuring out SM in flutter but it has taken well over a week!