Thread-safe Cached Enumerator - lock with yield

前端 未结 2 1112
轮回少年
轮回少年 2021-01-15 03:55

I have a custom \"CachedEnumerable\" class (inspired by Caching IEnumerable) that I need to make thread safe for my asp.net core web app.

Is the following implementa

2条回答
  •  隐瞒了意图╮
    2021-01-15 04:04

    The access to cache, yes it is thread safe, only one thread per time can read from _cache object.

    But in that way you can't assure that all threads gets elements in the same order as they access to GetEnumerator.

    Check these two exaples, if the behavior is what you expect, you can use lock in that way.

    Example 1:

    THREAD1 Calls GetEnumerator

    THREAD1 Initialize T current;

    THREAD2 Calls GetEnumerator

    THREAD2 Initialize T current;

    THREAD2 LOCK THREAD

    THREAD1 WAIT

    THREAD2 read from cache safely _cache[0]

    THREAD2 index++

    THREAD2 UNLOCK

    THREAD1 LOCK

    THREAD1 read from cache safely _cache[1]

    THREAD1 i++

    THREAD1 UNLOCK

    THREAD2 yield return current;

    THREAD1 yield return current;


    Example 2:

    THREAD2 Initialize T current;

    THREAD2 LOCK THREAD

    THREAD2 read from cache safely

    THREAD2 UNLOCK

    THREAD1 Initialize T current;

    THREAD1 LOCK THREAD

    THREAD1 read from cache safely

    THREAD1 UNLOCK

    THREAD1 yield return current;

    THREAD2 yield return current;

提交回复
热议问题