小编Sea*_*ton的帖子

ReaderWriterLockSlim扩展方法性能

我一直在玩集合和线程,并且遇到了人们创建的漂亮的扩展方法,通过允许IDisposable模式来简化ReaderWriterLockSlim的使用.

但是,我相信我已经意识到实施中的某些东西是性能杀手.我意识到扩展方法不应该真正影响性能,所以我假设实现中的某些东西是原因......创建/收集了一次性结构的数量?

这是一些测试代码:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;

namespace LockPlay {

    static class RWLSExtension {
        struct Disposable : IDisposable {
            readonly Action _action;
            public Disposable(Action action) {
                _action = action;
            }
            public void Dispose() {
                _action();
            }
        } // end struct
        public static IDisposable ReadLock(this ReaderWriterLockSlim rwls) {
            rwls.EnterReadLock();
            return new Disposable(rwls.ExitReadLock);
        }
        public static IDisposable UpgradableReadLock(this ReaderWriterLockSlim rwls) {
            rwls.EnterUpgradeableReadLock();
            return new Disposable(rwls.ExitUpgradeableReadLock);
        }
        public static IDisposable WriteLock(this ReaderWriterLockSlim rwls) {
            rwls.EnterWriteLock();
            return new Disposable(rwls.ExitWriteLock);
        } …
Run Code Online (Sandbox Code Playgroud)

c# performance extension-methods multithreading locking

8
推荐指数
2
解决办法
4629
查看次数