Is there anything wrong with await Task.Run(() => semaphore.WaitOne())?

后端 未结 2 1936
遥遥无期
遥遥无期 2020-12-31 18:28

Title says it all. Is there anything wrong with await Task.Run(() => semaphore.WaitOne());? System.Threading.Semaphore isn\'t thread-affine, so

2条回答
  •  抹茶落季
    2020-12-31 18:46

    You can use a SemaphoreSlim(0, 1) WITH your Semaphore , and WaitAsync before waiting for your original semaphore. This would ensure that for each process, only one thread is blocked waiting for the original Semaphore, and the others, while (a)waiting for WaitAsync, is not blocked.

    Another solution is to use the exclusive scheduler of ConcurrentExclusiveSchedulerPair.

提交回复
热议问题