System.Threading.ReaderWriterLockSlim.EnterReadLock()

Here are the examples of the csharp api System.Threading.ReaderWriterLockSlim.EnterReadLock() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

773 Examples 7

19 View Source File : CryptoConfig2.cs
License : MIT License
Project Creator : microsoftarchive

public static object CreateFromName(string name)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            // First try to use standard CryptoConfig to create the algorithm
            object cryptoConfigAlgorithm = CryptoConfig.CreateFromName(name);
            if (cryptoConfigAlgorithm != null)
            {
                return cryptoConfigAlgorithm;
            }

            // If we couldn't find the algorithm in crypto config, see if we have an internal mapping for
            // the name
            s_algorithmMapLock.EnterReadLock();
            try
            {
                Type cryptoConfig2Type = null;
                if (s_algorithmMap.TryGetValue(name, out cryptoConfig2Type))
                {
                    return Activator.CreateInstance(cryptoConfig2Type);
                }
            }
            finally
            {
                s_algorithmMapLock.ExitReadLock();
            }

            // Otherwise we don't know how to create this type, so just return null
            return null;
        }

19 View Source File : SessionTokenCache.cs
License : MIT License
Project Creator : microsoftgraph

public string ReadUserStateValue()
    {
      string state = string.Empty;
      SessionLock.EnterReadLock();
      state = (string)httpContext.Session[CacheId + "_state"];
      SessionLock.ExitReadLock();
      return state;
    }

19 View Source File : SessionTokenCache.cs
License : MIT License
Project Creator : microsoftgraph

public void Load()
    {
      SessionLock.EnterReadLock();
      cache.Deserialize((byte[])httpContext.Session[CacheId]);
      SessionLock.ExitReadLock();
    }

19 View Source File : PuncherServer.cs
License : MIT License
Project Creator : MidLevel

private void ProcessMessage()
        {
            int receiveSize = Transport.ReceiveFrom(_buffer, 0, _buffer.Length, -1, out IPEndPoint senderEndpoint);

            // Address
            IPAddress senderAddress = senderEndpoint.Address;

            if (receiveSize != _buffer.Length)
            {
                return;
            }

            if (_buffer[0] != (byte)MessageType.Register)
            {
                return;
            }

            // Register client packet
            byte registerFlags = _buffer[1];
            bool isConnector = (registerFlags & 1) == 1;
            bool isListener = ((registerFlags >> 1) & 1) == 1;

            if (isListener)
            {
                _listenerClientsLock.EnterUpgradeableReadLock();

                try
                {
                    if (_listenerClients.TryGetValue(senderAddress, out Client client))
                    {
                        _listenerClientsLock.EnterWriteLock();

                        try
                        {
                            client.EndPoint = senderEndpoint;
                            client.IsConnector = isConnector;
                            client.IsListener = isListener;
                            client.LastRegisterTime = DateTime.Now;
                        }
                        finally
                        {
                            _listenerClientsLock.ExitWriteLock();
                        }
                    }
                    else
                    {
                        _listenerClientsLock.EnterWriteLock();

                        try
                        {
                            _listenerClients.Add(senderAddress, new Client()
                            {
                                EndPoint = senderEndpoint,
                                IsConnector = isConnector,
                                IsListener = isListener,
                                LastRegisterTime = DateTime.Now
                            });
                        }
                        finally
                        {
                            _listenerClientsLock.ExitWriteLock();
                        }
                    }
                }
                finally
                {
                    _listenerClientsLock.ExitUpgradeableReadLock();
                }

                // Prevent info leaks
                Array.Clear(_buffer, 0, _buffer.Length);

                // Write message type
                _buffer[0] = (byte)MessageType.Registered;

                // Send to listener
                Transport.SendTo(_buffer, 0, _buffer.Length, -1, senderEndpoint);
            }

            if (isConnector)
            {
                // Copy address to address buffer
                Buffer.BlockCopy(_buffer, 2, _ipBuffer, 0, 4);

                // Parse address
                IPAddress listenerAddress = new IPAddress(_ipBuffer);

                // Read token size
                byte tokenSize = _buffer[6];

                // Validate token size
                if (tokenSize > _buffer.Length - 6)
                {
                    // Invalid token size
                    return;
                }

                // Copy token to token buffer
                Buffer.BlockCopy(_buffer, 7, _tokenBuffer, 0, tokenSize);

                _listenerClientsLock.EnterReadLock();

                try
                {
                    // Look for the client they wish to connec tto
                    if (_listenerClients.TryGetValue(listenerAddress, out Client listenerClient) && listenerClient.IsListener)
                    {
                        // Write message type
                        _buffer[0] = (byte)MessageType.ConnectTo;

                        // Write address
                        Buffer.BlockCopy(listenerClient.EndPoint.Address.GetAddressBytes(), 0, _buffer, 1, 4);

                        // Write port
                        _buffer[5] = (byte)listenerClient.EndPoint.Port;
                        _buffer[6] = (byte)(listenerClient.EndPoint.Port >> 8);

                        // Write token length
                        _buffer[7] = tokenSize;

                        // Write token
                        Buffer.BlockCopy(_tokenBuffer, 0, _buffer, 8, tokenSize);

                        // Send to connector
                        Transport.SendTo(_buffer, 0, _buffer.Length, -1, senderEndpoint);

                        // Write address
                        Buffer.BlockCopy(senderAddress.GetAddressBytes(), 0, _buffer, 1, 4);

                        // Write port
                        _buffer[5] = (byte)senderEndpoint.Port;
                        _buffer[6] = (byte)(senderEndpoint.Port >> 8);

                        // Send to listener
                        Transport.SendTo(_buffer, 0, _buffer.Length, -1, listenerClient.EndPoint);
                    }
                    else
                    {
                        // Prevent info leaks
                        Array.Clear(_buffer, 0, _buffer.Length);

                        _buffer[0] = (byte)MessageType.Error;
                        _buffer[1] = (byte)ErrorType.ClientNotFound;

                        // Send error
                        Transport.SendTo(_buffer, 0, _buffer.Length, -1, senderEndpoint);
                    }
                }
                finally
                {
                    _listenerClientsLock.ExitReadLock();
                }
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

internal void HandleMTUResponse(uint size)
        {
            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.Connected)
                {
                    // Calculate the new MTU
                    int attemptedMtu = (int)(MTU * Config.MTUGrowthFactor);

                    if (attemptedMtu > Config.MaximumMTU)
                    {
                        attemptedMtu = Config.MaximumMTU;
                    }

                    if (attemptedMtu < Config.MinimumMTU)
                    {
                        attemptedMtu = Config.MinimumMTU;
                    }

                    if (attemptedMtu == size)
                    {
                        // This is a valid response

                        if (Merger != null)
                        {
                            Merger.ExpandToSize((int)attemptedMtu);
                        }

                        // Set new MTU
                        MTU = (ushort)attemptedMtu;

                        // Set new status
                        MTUStatus = new MessageStatus()
                        {
                            Attempts = 0,
                            HasAcked = false,
                            LastAttempt = NetTime.MinValue
                        };

                        if (Logging.CurrentLogLevel <= LogLevel.Debug) Logging.LogInfo("Client " + EndPoint + " MTU was increased to " + MTU);
                    }
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

private void CheckConnectionResends()
        {
            _stateLock.EnterReadLock();

            try
            {
                switch (State)
                {
                    case ConnectionState.RequestingConnection:
                        {
                            if ((!Config.TimeBasedConnectionChallenge || PreConnectionChallengeSolved) && (NetTime.Now - HandshakeLastSendTime).TotalMilliseconds > Config.ConnectionRequestMinResendDelay && HandshakeResendAttempts <= Config.MaxConnectionRequestResends)
                            {
                                HandshakeResendAttempts++;
                                HandshakeLastSendTime = NetTime.Now;

                                // Calculate the minimum size we can fit the packet in
                                int minSize = 1 + Constants.RUFFLES_PROTOCOL_IDENTIFICATION.Length + (Config.TimeBasedConnectionChallenge ? sizeof(ulong) * 3 : 0);

                                // Calculate the actual size with respect to amplification padding
                                int size = Math.Max(minSize, (int)Config.AmplificationPreventionHandshakePadding);

                                // Allocate memory
                                HeapMemory memory = MemoryManager.AllocHeapMemory((uint)size);

                                // Write the header
                                memory.Buffer[0] = HeaderPacker.Pack((byte)MessageType.ConnectionRequest);

                                // Copy the identification token
                                Buffer.BlockCopy(Constants.RUFFLES_PROTOCOL_IDENTIFICATION, 0, memory.Buffer, 1, Constants.RUFFLES_PROTOCOL_IDENTIFICATION.Length);

                                if (Config.TimeBasedConnectionChallenge)
                                {
                                    // Write the response unix time
                                    for (byte x = 0; x < sizeof(ulong); x++) memory.Buffer[1 + Constants.RUFFLES_PROTOCOL_IDENTIFICATION.Length + x] = ((byte)(PreConnectionChallengeTimestamp >> (x * 8)));

                                    // Write counter
                                    for (byte x = 0; x < sizeof(ulong); x++) memory.Buffer[1 + Constants.RUFFLES_PROTOCOL_IDENTIFICATION.Length + sizeof(ulong) + x] = ((byte)(PreConnectionChallengeCounter >> (x * 8)));

                                    // Write IV
                                    for (byte x = 0; x < sizeof(ulong); x++) memory.Buffer[1 + Constants.RUFFLES_PROTOCOL_IDENTIFICATION.Length + (sizeof(ulong) * 2) + x] = ((byte)(PreConnectionChallengeIV >> (x * 8)));

                                    // Print debug
                                    if (Logging.CurrentLogLevel <= LogLevel.Debug) Logging.LogInfo("Resending ConnectionRequest with challenge [Counter=" + PreConnectionChallengeCounter + "] [IV=" + PreConnectionChallengeIV + "] [Time=" + PreConnectionChallengeTimestamp + "] [Hash=" + HashProvider.GetStableHash64(PreConnectionChallengeTimestamp, PreConnectionChallengeCounter, PreConnectionChallengeIV) + "]");
                                }
                                else
                                {
                                    // Print debug
                                    if (Logging.CurrentLogLevel <= LogLevel.Debug) Logging.LogInfo("Resending ConnectionRequest");
                                }

                                SendInternal(new ArraySegment<byte>(memory.Buffer, 0, (int)memory.VirtualCount), true);

                                // Release memory
                                MemoryManager.DeAlloc(memory);
                            }
                        }
                        break;
                    case ConnectionState.RequestingChallenge:
                        {
                            if ((NetTime.Now - HandshakeLastSendTime).TotalMilliseconds > Config.HandshakeResendDelay && HandshakeResendAttempts <= Config.MaxHandshakeResends)
                            {
                                // Resend challenge request
                                SendChallengeRequest();
                            }
                        }
                        break;
                    case ConnectionState.SolvingChallenge:
                        {
                            if ((NetTime.Now - HandshakeLastSendTime).TotalMilliseconds > Config.HandshakeResendDelay && HandshakeResendAttempts <= Config.MaxHandshakeResends)
                            {
                                // Resend response
                                SendChallengeResponse();
                            }
                        }
                        break;
                    case ConnectionState.Connected:
                        {
                            if (!HailStatus.HasAcked && (NetTime.Now - HailStatus.LastAttempt).TotalMilliseconds > Config.HandshakeResendDelay && HailStatus.Attempts <= Config.MaxHandshakeResends)
                            {
                                // Resend hail
                                SendHail();
                            }
                        }
                        break;
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

internal void HandleHeartbeat(ArraySegment<byte> payload)
        {
            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.Connected)
                {
                    HeapPointers pointers = HeartbeatChannel.HandleIncomingMessagePoll(payload);

                    if (pointers != null)
                    {
                        MemoryWrapper wrapper = (MemoryWrapper)pointers.Pointers[0];

                        if (wrapper != null)
                        {
                            if (wrapper.AllocatedMemory != null)
                            {
                                LastMessageIn = NetTime.Now;

                                // Dealloc the memory
                                MemoryManager.DeAlloc(wrapper.AllocatedMemory);
                            }

                            if (wrapper.DirectMemory != null)
                            {
                                LastMessageIn = NetTime.Now;
                            }

                            // Dealloc the wrapper
                            MemoryManager.DeAlloc(wrapper);
                        }

                        // Dealloc the pointers
                        MemoryManager.DeAlloc(pointers);
                    }
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

internal bool HandleChannelSend(ArraySegment<byte> data, byte channelId, bool noMerge, ulong notificationKey)
        {
            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.Connected)
                {
                    // Send the data
                    ChannelRouter.CreateOutgoingMessage(data, this, channelId, noMerge, notificationKey);

                    return true;
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }

            return false;
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

internal void HandleChannelData(ArraySegment<byte> payload)
        {
            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.Connected)
                {
                    LastMessageIn = NetTime.Now;

                    ChannelRouter.HandleIncomingMessage(payload, this, Config, MemoryManager);
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

internal void HandleChannelAck(ArraySegment<byte> payload)
        {
            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.Connected)
                {
                    LastMessageIn = NetTime.Now;

                    ChannelRouter.HandleIncomingAck(payload, this, Config, MemoryManager);
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

internal void HandleHailConfirmed()
        {
            // If the state is changed during a confirmation it does not matter. No shared data is used except the HailStatus which is fine.
            // If reusing connection, this could become a race.
            // TODO: Remove lock

            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.Connected && !HailStatus.HasAcked)
                {
                    LastMessageIn = NetTime.Now;
                    HailStatus.HasAcked = true;
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

private void RunPathMTU()
        {
            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.Connected && MTU < Config.MaximumMTU && MTUStatus.Attempts < Config.MaxMTUAttempts && (NetTime.Now - MTUStatus.LastAttempt).TotalMilliseconds > Config.MTUAttemptDelay)
                {
                    int attemptedMtu = (int)(MTU * Config.MTUGrowthFactor);

                    if (attemptedMtu > Config.MaximumMTU)
                    {
                        attemptedMtu = Config.MaximumMTU;
                    }

                    if (attemptedMtu < Config.MinimumMTU)
                    {
                        attemptedMtu = Config.MinimumMTU;
                    }

                    MTUStatus.Attempts++;
                    MTUStatus.LastAttempt = NetTime.Now;

                    // Allocate memory
                    HeapMemory memory = MemoryManager.AllocHeapMemory((uint)attemptedMtu);

                    // Set the header
                    memory.Buffer[0] = HeaderPacker.Pack(MessageType.MTURequest);

                    // Send the request
                    SendInternal(new ArraySegment<byte>(memory.Buffer, 0, (int)memory.VirtualCount), true);

                    // Dealloc the memory
                    MemoryManager.DeAlloc(memory);
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

private void CheckConnectionTimeouts()
        {
            _stateLock.EnterReadLock();

            bool timeout = false;

            try
            {
                if (State == ConnectionState.RequestingConnection)
                {
                    if ((NetTime.Now - ConnectionStarted).TotalMilliseconds > Config.ConnectionRequestTimeout)
                    {
                        // This client has taken too long to connect. Let it go.
                        // TODO: This log can race and show multiple times
                        if (Logging.CurrentLogLevel <= LogLevel.Info) Logging.LogInfo("Disconnecting client because handshake was not started");

                        timeout = true;
                    }
                }
                else if (State != ConnectionState.Connected)
                {
                    // They are not requesting connection. But they are not connected. This means they are doing a handshake
                    if ((NetTime.Now - HandshakeStarted).TotalMilliseconds > Config.HandshakeTimeout)
                    {
                        // This client has taken too long to connect. Let it go.
                        // TODO: This log can race and show multiple times
                       if (Logging.CurrentLogLevel <= LogLevel.Info) Logging.LogInfo("Disconnecting client because it took too long to complete the handshake");

                        timeout = true;
                    }
                }
                else
                {
                    if ((NetTime.Now - LastMessageIn).TotalMilliseconds > Config.ConnectionTimeout)
                    {
                        // This client has not answered us in way too long. Let it go
                        // TODO: This log can race and show multiple times
                        if (Logging.CurrentLogLevel <= LogLevel.Info) Logging.LogInfo("Disconnecting client because no incoming message has been received");

                        timeout = true;
                    }
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }

            if (timeout)
            {
                DisconnectInternal(false, true);
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

private void CheckConnectionHeartbeats()
        {
            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.Connected)
                {
                    if ((NetTime.Now - LastMessageOut).TotalMilliseconds > Config.HeartbeatDelay)
                    {
                        // This client has not been talked to in a long time. Send a heartbeat.

                        // Create sequenced heartbeat packet
                        HeapMemory heartbeatMemory = HeartbeatChannel.CreateOutgoingHeartbeatMessage();

                        // Send heartbeat
                        SendInternal(new ArraySegment<byte>(heartbeatMemory.Buffer, (int)heartbeatMemory.VirtualOffset, (int)heartbeatMemory.VirtualCount), false);

                        // DeAlloc the memory
                        MemoryManager.DeAlloc(heartbeatMemory);
                    }
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

internal void HandleMTURequest(uint size)
        {
            // This does not access anything shared. We thus dont need to lock the state. If the state is raced or outdated its no harm done.
            // TODO: Remove lock

            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.Connected)
                {
                    // Alloc memory for response
                    HeapMemory memory = MemoryManager.AllocHeapMemory(size);

                    // Write the header
                    memory.Buffer[0] = HeaderPacker.Pack(MessageType.MTUResponse);

                    // Send the response
                    SendInternal(new ArraySegment<byte>(memory.Buffer, 0, (int)memory.VirtualCount), true);

                    // Dealloc the memory
                    MemoryManager.DeAlloc(memory);
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

internal void HandleChallengeRequest(ulong challenge, byte difficulty)
        {
            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.RequestingConnection)
                {
                    LastMessageIn = NetTime.Now;

                    // Solve the hashcash
                    if (HashCash.TrySolve(challenge, difficulty, ulong.MaxValue, out ulong additionsRequired))
                    {
                        if (Logging.CurrentLogLevel <= LogLevel.Debug) Logging.LogInfo("Solved the challenge");

                        // Set the solved results
                        ConnectionChallenge = challenge;
                        ChallengeDifficulty = difficulty;
                        ChallengeAnswer = additionsRequired;

                        // Set resend values
                        HandshakeResendAttempts = 0;
                        HandshakeStarted = NetTime.Now;
                        HandshakeLastSendTime = NetTime.Now;
                        State = ConnectionState.SolvingChallenge;

                        // Send the response
                        SendChallengeResponse();
                    }
                    else
                    {
                        // Failed to solve
                        if (Logging.CurrentLogLevel <= LogLevel.Error) Logging.LogError("Failed to solve the challenge");
                    }
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

private void RunChannelUpdates()
        {
            bool timeout = false;

            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.Connected)
                {
                    for (int i = 0; i < Channels.Length; i++)
                    {
                        if (Channels[i] != null)
                        {
                            Channels[i].InternalUpdate(out bool _timeout);

                            timeout |= _timeout;
                        }
                    }
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }

            if (timeout)
            {
                DisconnectInternal(false, true);
            }
        }

19 View Source File : Connection.cs
License : MIT License
Project Creator : MidLevel

private void CheckMergedPackets()
        {
            _stateLock.EnterReadLock();

            try
            {
                if (State == ConnectionState.Connected)
                {
                    ArraySegment<byte>? mergedPayload = Merger.TryFlush(false);

                    if (mergedPayload != null)
                    {
                        SendInternal(mergedPayload.Value, true);
                    }
                }
            }
            finally
            {
                _stateLock.ExitReadLock();
            }
        }

19 View Source File : ConcurrentFile.cs
License : GNU Affero General Public License v3.0
Project Creator : Milkitic

public static byte[] ReadAllBytes(string path)
        {
            path = GetFormattedPath(path);
            var cacheLock = LockDic.GetOrAdd(path, new ReaderWriterLockSlim());
            cacheLock.EnterReadLock();
            try
            {
                return SysIO.File.ReadAllBytes(path);
            }
            finally
            {
                cacheLock.ExitReadLock();
            }
        }

19 View Source File : ConcurrentFile.cs
License : GNU Affero General Public License v3.0
Project Creator : Milkitic

public static string[] ReadAllLines(string path)
        {
            path = GetFormattedPath(path);
            var cacheLock = LockDic.GetOrAdd(path, new ReaderWriterLockSlim());
            cacheLock.EnterReadLock();
            try
            {
                return SysIO.File.ReadAllLines(path);
            }
            finally
            {
                cacheLock.ExitReadLock();
            }
        }

19 View Source File : ConcurrentFile.cs
License : GNU Affero General Public License v3.0
Project Creator : Milkitic

public static string ReadAllText(string path)
        {
            path = GetFormattedPath(path);
            var cacheLock = LockDic.GetOrAdd(path, new ReaderWriterLockSlim());
            cacheLock.EnterReadLock();
            try
            {
                return SysIO.File.ReadAllText(path);
            }
            finally
            {
                cacheLock.ExitReadLock();
            }
        }

19 View Source File : LockExtensions.cs
License : MIT License
Project Creator : mode51

public static void Lock(this ReaderWriterLockSlim @this, LockTypeEnum lockType)
        {
            if (lockType == LockTypeEnum.Read)
                @this.EnterReadLock();
            else
                @this.EnterWriteLock();
        }

19 View Source File : ReaderWriterLocker.cs
License : MIT License
Project Creator : mode51

public void Lock(LockTypeEnum lockType)
        {
            if (lockType == LockTypeEnum.Read)
                Locker.EnterReadLock();
            else
                Locker.EnterWriteLock();
        }

19 View Source File : AggregateAssetBundle.cs
License : GNU General Public License v3.0
Project Creator : mrojkov

public override byte[] GetCookingRulesSHA1(string path)
		{
			sync.EnterReadLock();
			try {
				foreach (var bundle in bundles) {
					if (bundle.FileExists(path)) {
						return bundle.GetCookingRulesSHA1(path);
					}
				}
			} finally {
				sync.ExitReadLock();
			}
			throw new InvalidOperationException($"Path {path} not found in aggregate replacedet bundle.");
		}

19 View Source File : AggregateAssetBundle.cs
License : GNU General Public License v3.0
Project Creator : mrojkov

public override Stream OpenFile(string path)
		{
			sync.EnterReadLock();
			try {
				foreach (var bundle in bundles) {
					if (bundle.FileExists(path)) {
						return bundle.OpenFile(path);
					}
				}
			} finally {
				sync.ExitReadLock();
			}
			throw new FileNotFoundException($"File {path} not found in aggregate replacedet bundle.");
		}

19 View Source File : AggregateAssetBundle.cs
License : GNU General Public License v3.0
Project Creator : mrojkov

public override DateTime GetFileLastWriteTime(string path)
		{
			sync.EnterReadLock();
			try {
				foreach (var bundle in bundles) {
					if (bundle.FileExists(path)) {
						return bundle.GetFileLastWriteTime(path);
					}
				}
			} finally {
				sync.ExitReadLock();
			}
			throw new InvalidOperationException($"Path {path} not found in aggregate replacedet bundle.");
		}

19 View Source File : AggregateAssetBundle.cs
License : GNU General Public License v3.0
Project Creator : mrojkov

public override int GetFileSize(string path)
		{
			sync.EnterReadLock();
			try {
				foreach (var bundle in bundles) {
					if (bundle.FileExists(path)) {
						return bundle.GetFileSize(path);
					}
				}
			} finally {
				sync.ExitReadLock();
			}
			throw new InvalidOperationException($"Path {path} not found in aggregate replacedet bundle.");
		}

19 View Source File : AggregateAssetBundle.cs
License : GNU General Public License v3.0
Project Creator : mrojkov

public override bool FileExists(string path)
		{
			sync.EnterReadLock();
			try {
				foreach (var bundle in bundles) {
					if (bundle.FileExists(path)) {
						return true;
					}
				}
			} finally {
				sync.ExitReadLock();
			}
			return false;
		}

19 View Source File : AggregateAssetBundle.cs
License : GNU General Public License v3.0
Project Creator : mrojkov

public override IEnumerable<string> EnumerateFiles(string path = null)
		{
			sync.EnterReadLock();
			try {
				return bundles.SelectMany(bundle => bundle.EnumerateFiles(path));
			} finally {
				sync.ExitReadLock();
			}
		}

19 View Source File : CapCache.cs
License : MIT License
Project Creator : msdn129

public T Get(K key)
        {
            if (disposed)
            {
                return default(T);
            }

            _locker.EnterReadLock();
            try
            {
                T rv;
                return _cache.TryGetValue(key, out rv) ? rv : default(T);
            }
            finally
            {
                _locker.ExitReadLock();
            }
        }

19 View Source File : CapCache.cs
License : MIT License
Project Creator : msdn129

public bool TryGet(K key, out T value)
        {
            if (disposed)
            {
                value = default(T);
                return false;
            }

            _locker.EnterReadLock();
            try
            {
                return _cache.TryGetValue(key, out value);
            }
            finally
            {
                _locker.ExitReadLock();
            }
        }

19 View Source File : CapCache.cs
License : MIT License
Project Creator : msdn129

public bool Exists(K key)
        {
            if (disposed)
            {
                return false;
            }

            _locker.EnterReadLock();
            try
            {
                return _cache.ContainsKey(key);
            }
            finally
            {
                _locker.ExitReadLock();
            }
        }

19 View Source File : MessageEvents.cs
License : GNU General Public License v2.0
Project Creator : nesherhh

protected override void WndProc(ref Message m)
			{
				rwLock.EnterReadLock();
				bool shouldHandle = messages.ContainsKey(m.Msg);
				rwLock.ExitReadLock();

				if (shouldHandle)
				{
					context.Post(state =>
								 {
									 EventHandler<MessageReceivedEventArgs> handler = MessageReceived;
									 if (handler != null)
										 handler(null, new MessageReceivedEventArgs((Message)state));
								 }, m);
				}
				base.WndProc(ref m);
			}

19 View Source File : MultipointMouseProvider.cs
License : GNU General Public License v2.0
Project Creator : nesherhh

void OnMouseUp(IntPtr handle, double x, double y, double oldX, double oldY)
		{
			currentListLock.EnterReadLock();
			historyListLock.EnterWriteLock();

			var contactInfo = currentList[handle];
			//contactInfo.PreviousCenter = new Point(oldX, oldY);
			historyList[handle] = contactInfo;

			historyListLock.ExitWriteLock();
			currentListLock.ExitReadLock();
			currentListLock.EnterWriteLock();

			currentList.Remove(handle);
			
			currentListLock.ExitWriteLock();

			//MouseEmulation.Action(x, y, MouseEmulation.MouseAction.LeftUp);
		}

19 View Source File : MultipointMouseProvider.cs
License : GNU General Public License v2.0
Project Creator : nesherhh

void OnMouseMove(IntPtr handle, double x, double y, double oldX, double oldY)
		{
			ContactInfo contact = new ContactInfo(new Rect(x, y, 10, 10));
			
			currentListLock.EnterReadLock();
			ContactInfo oldContact = currentList[handle];
			currentListLock.ExitReadLock();

			contact.Id = oldContact.Id;
			if (contact.Id == -1)
			{
				contact.Delta = new Vector();
				contact.DeltaArea = 0;
				contact.PredictedPos = contact.Center;
				contact.Displacement = new Vector();
			}
			else
			{
				contact.Delta = contact.Center - oldContact.Center;
				contact.DeltaArea = contact.Area - oldContact.Area;
				contact.PredictedPos = contact.Center + contact.Delta;
				contact.Displacement = oldContact.Displacement + contact.Delta;
				contact.PreviousCenter = oldContact.PreviousCenter;
			}
			historyListLock.EnterWriteLock();

			historyList[handle] = oldContact;

			historyListLock.ExitWriteLock();
			currentListLock.EnterWriteLock();

			currentList[handle] = contact;

			currentListLock.ExitWriteLock();

			//MouseEmulation.Action(x, y, MouseEmulation.MouseAction.Move);
		}

19 View Source File : MultipointMouseProvider.cs
License : GNU General Public License v2.0
Project Creator : nesherhh

protected override ContactInfo[] GetContactsCore()
		{
			nextFrame.WaitOne();

			List<ContactInfo> result = new List<ContactInfo>();

			currentListLock.EnterReadLock();
			Dictionary<IntPtr, ContactInfo> currentListCopy = new Dictionary<IntPtr,ContactInfo>(currentList);
			currentListLock.ExitReadLock();

			foreach (KeyValuePair<IntPtr, ContactInfo> pair in currentListCopy)
			{
				ContactInfo currentContact = pair.Value;
				if (currentContact.Id == -1)
				{
					currentContact.Id = currentId;
					currentId++;
					if (currentId >= 65535)
						currentId = 1;

					currentContact.State = ContactState.Down;
					result.Add(currentContact);
				}
				else
				{
					currentContact.State = ContactState.Move;
					result.Add(currentContact);
				}
			}

			List<IntPtr> toRemove = new List<IntPtr>();

			historyListLock.EnterReadLock();
			Dictionary<IntPtr, ContactInfo> historyListCopy = new Dictionary<IntPtr,ContactInfo>(historyList);
			historyListLock.ExitReadLock();

			foreach (KeyValuePair<IntPtr, ContactInfo> pair in historyListCopy)
			{
				ContactInfo previousContact = pair.Value;
				bool found = false;
				foreach (ContactInfo currentContact in currentListCopy.Values)
				{
					if (currentContact.Id == previousContact.Id)
					{
						found = true;
						break;
					}
				}

				if (!found)
				{
					previousContact.State = ContactState.Up;
					result.Add(previousContact);
					toRemove.Add(pair.Key);
				}
			}

			historyListLock.EnterWriteLock();
			foreach (IntPtr key in toRemove)
				historyList.Remove(key);
			historyListLock.ExitWriteLock();

			//PreviewInputOutput();

			return result.ToArray();
		}

19 View Source File : MultipointMouseProvider.cs
License : GNU General Public License v2.0
Project Creator : nesherhh

private void PreviewInputOutput()
		{
			if (ShowPreview && (inputPreviewHandler != null || outputPreviewHandler != null))
			{
				RenderTargetBitmap renderToBitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);

				DrawingVisual visual = new DrawingVisual();
				DrawingContext drawingContext = visual.RenderOpen();

				currentListLock.EnterReadLock();
				Dictionary<IntPtr, ContactInfo> currentListCopy = new Dictionary<IntPtr, ContactInfo>(currentList);
				currentListLock.ExitReadLock();

				foreach (KeyValuePair<IntPtr, ContactInfo> pair in currentListCopy)
				{
					ContactInfo contactInfo = pair.Value;
					drawingContext.DrawEllipse(Brushes.White, new Pen(), contactInfo.Center, contactInfo.Rectangle.Width,
											   contactInfo.Rectangle.Height);
				}
				drawingContext.Close();

				renderToBitmap.Render(visual);

				int stride = renderToBitmap.Format.GetStride(renderToBitmap.PixelWidth);
				byte[] pixels = new byte[renderToBitmap.PixelHeight * stride];
				renderToBitmap.CopyPixels(pixels, stride, 0);

				if (inputPreviewHandler != null)
					inputPreviewHandler(width, height, bitPerPixel, pixels);
				if (outputPreviewHandler != null)
					outputPreviewHandler(width, height, bitPerPixel, pixels);
			}
		}

19 View Source File : ErrorEventAggregator.cs
License : Apache License 2.0
Project Creator : newrelic

public override void Collect(ErrorEventWireModel errorEventWireModel)
        {
            _agentHealthReporter.ReportErrorEventSeen();

            _readerWriterLock.EnterReadLock();
            try
            {
                AddEventToCollection(errorEventWireModel);
            }
            finally
            {
                _readerWriterLock.ExitReadLock();
            }
        }

19 View Source File : CustomEventAggregator.cs
License : Apache License 2.0
Project Creator : newrelic

public override void Collect(CustomEventWireModel customEventWireModel)
        {
            _agentHealthReporter.ReportCustomEventCollected();

            _readerWriterLockSlim.EnterReadLock();
            try
            {
                _customEvents.Add(new PrioritizedNode<CustomEventWireModel>(customEventWireModel));
            }
            finally
            {
                _readerWriterLockSlim.ExitReadLock();
            }
        }

19 View Source File : ErrorTraceAggregator.cs
License : Apache License 2.0
Project Creator : newrelic

public override void Collect(ErrorTraceWireModel errorTraceWireModel)
        {
            _agentHealthReporter.ReportErrorTraceCollected();

            _readerWriterLock.EnterReadLock();
            try
            {
                AddToCollection(errorTraceWireModel);
            }
            finally
            {
                _readerWriterLock.ExitReadLock();
            }
        }

19 View Source File : TransactionEventAggregator.cs
License : Apache License 2.0
Project Creator : newrelic

public override void Collect(TransactionEventWireModel transactionEventWireModel)
        {
            _agentHealthReporter.ReportTransactionEventCollected();

            _readerWriterLock.EnterReadLock();
            try
            {
                AddEventToCollection(transactionEventWireModel);
            }
            finally
            {
                _readerWriterLock.ExitReadLock();
            }
        }

19 View Source File : SpanEventAggregator.cs
License : Apache License 2.0
Project Creator : newrelic

public override void Collect(ISpanEventWireModel wireModel)
        {
            _agentHealthReporter.ReportSpanEventCollected(1);

            _readerWriterLockSlim.EnterReadLock();
            try
            {
                _spanEvents.Add(new PrioritizedNode<ISpanEventWireModel>(wireModel));
            }
            finally
            {
                _readerWriterLockSlim.ExitReadLock();
            }
        }

19 View Source File : SpanEventAggregator.cs
License : Apache License 2.0
Project Creator : newrelic

public void Collect(IEnumerable<ISpanEventWireModel> wireModels)
        {
            int added;
            _readerWriterLockSlim.EnterReadLock();
            try
            {
                added = AddWireModels(wireModels);
            }
            finally
            {
                _readerWriterLockSlim.ExitReadLock();
            }
            _agentHealthReporter.ReportSpanEventCollected(added);
        }

19 View Source File : IDatabase.cs
License : GNU Affero General Public License v3.0
Project Creator : NiclasOlofsson

public byte[] Get(Span<byte> key)
		{
			_dbLock.EnterReadLock();

			try
			{
				if (_manifest == null) throw new InvalidOperationException("No manifest for database. Did you open it?");
				if (_memCache == null) throw new InvalidOperationException("No current memory cache for database. Did you open it?");

				ResultStatus result = _memCache.Get(key);
				if (result.State == ResultState.Deleted || result.State == ResultState.Exist)
				{
					if (result.Data == ReadOnlySpan<byte>.Empty) return null;
					return result.Data.ToArray();
				}
				MemCache imm = _immutableMemCache;
				if (imm != null)
				{
					result = imm.Get(key);
					if (result.State == ResultState.Deleted || result.State == ResultState.Exist)
					{
						if (result.Data == ReadOnlySpan<byte>.Empty) return null;
						return result.Data.ToArray();
					}
				}

				result = _manifest.Get(key);
				if (result.Data == ReadOnlySpan<byte>.Empty) return null;
				return result.Data.ToArray();
			}
			finally
			{
				_dbLock.ExitReadLock();
			}
		}

19 View Source File : SessionTokenStore.cs
License : MIT License
Project Creator : nicolonsky

public CachedUser GetUserDetails()
        {
            sessionLock.EnterReadLock();
            var cachedUser = JsonConvert.DeserializeObject<CachedUser>((string)httpContext.Session[userCacheKey]);
            sessionLock.ExitReadLock();
            return cachedUser;
        }

19 View Source File : SessionTokenStore.cs
License : MIT License
Project Creator : nicolonsky

private void BeforeAccessNotification(TokenCacheNotificationArgs args)
        {
            sessionLock.EnterReadLock();

            try
            {
                // Load the cache from the session
                args.TokenCache.DeserializeMsalV3((byte[])httpContext.Session[tokenCacheKey]);
            }
            finally
            {
                sessionLock.ExitReadLock();
            }
        }

19 View Source File : NetManager.cs
License : MIT License
Project Creator : nievesj

private bool TryGetPeer(IPEndPoint endPoint, out NetPeer peer)
        {
            _peersLock.EnterReadLock();
            bool result = _peersDict.TryGetValue(endPoint, out peer);
            _peersLock.ExitReadLock();
            return result;
        }

19 View Source File : NetManager.cs
License : MIT License
Project Creator : nievesj

private void DataReceived(byte[] reusableBuffer, int count, IPEndPoint remoteEndPoint)
        {
            if (EnableStatistics)
            {
                Statistics.PacketsReceived++;
                Statistics.BytesReceived += (uint)count;
            }

            if (_extraPacketLayer != null)
            {
                _extraPacketLayer.ProcessInboundPacket(ref reusableBuffer, ref count);
                if (count == 0)
                    return;
            }

            //empty packet
            if (reusableBuffer[0] == (byte) PacketProperty.Empty)
                return;

            //Try read packet
            NetPacket packet = NetPacketPool.GetPacket(count);
            if (!packet.FromBytes(reusableBuffer, 0, count))
            {
                NetPacketPool.Recycle(packet);
                NetDebug.WriteError("[NM] DataReceived: bad!");
                return;
            }

            switch (packet.Property)
            {
                //special case connect request
                case PacketProperty.ConnectRequest:
                    if (NetConnectRequestPacket.GetProtocolId(packet) != NetConstants.ProtocolId)
                    {
                        SendRawAndRecycle(NetPacketPool.GetWithProperty(PacketProperty.InvalidProtocol), remoteEndPoint);
                        return;
                    }
                    break;
                //unconnected messages
                case PacketProperty.Broadcast:
                    if (!BroadcastReceiveEnabled)
                        return;
                    CreateEvent(NetEvent.EType.Broadcast, remoteEndPoint: remoteEndPoint, readerSource: packet);
                    return;
                case PacketProperty.UnconnectedMessage:
                    if (!UnconnectedMessagesEnabled)
                        return;
                    CreateEvent(NetEvent.EType.ReceiveUnconnected, remoteEndPoint: remoteEndPoint, readerSource: packet);
                    return;
                case PacketProperty.NatMessage:
                    if (NatPunchEnabled)
                        NatPunchModule.ProcessMessage(remoteEndPoint, packet);
                    return;
            }

            //Check normal packets
            NetPeer netPeer;
            _peersLock.EnterReadLock();
            bool peerFound = _peersDict.TryGetValue(remoteEndPoint, out netPeer);
            _peersLock.ExitReadLock();
            
            switch (packet.Property)
            {
                case PacketProperty.ConnectRequest:
                    var connRequest = NetConnectRequestPacket.FromData(packet);
                    if (connRequest != null)
                        ProcessConnectRequest(remoteEndPoint, netPeer, connRequest);
                    break;
                case PacketProperty.PeerNotFound:
                    if (peerFound)
                    {
                        if (netPeer.ConnectionState != ConnectionState.Connected)
                            return;
                        if (packet.Size == 1) 
                        {
                            //first reply
                            var p = NetPacketPool.GetWithProperty(PacketProperty.PeerNotFound, 9);
                            p.RawData[1] = 0;
                            FastBitConverter.GetBytes(p.RawData, 2, netPeer.ConnectTime);
                            SendRawAndRecycle(p, remoteEndPoint);
                            NetDebug.Write("PeerNotFound sending connectTime: {0}", netPeer.ConnectTime);
                        }
                        else if (packet.Size == 10 && packet.RawData[1] == 1 && BitConverter.ToInt64(packet.RawData, 2) == netPeer.ConnectTime) 
                        {
                            //second reply
                            NetDebug.Write("PeerNotFound received our connectTime: {0}", netPeer.ConnectTime);
                            DisconnectPeerForce(netPeer, DisconnectReason.RemoteConnectionClose, 0, null);
                        }
                    }
                    else if (packet.Size == 10 && packet.RawData[1] == 0)
                    {
                        //send reply back
                        packet.RawData[1] = 1;
                        SendRawAndRecycle(packet, remoteEndPoint);
                    }
                    break;
                case PacketProperty.InvalidProtocol:
                    if (peerFound && netPeer.ConnectionState == ConnectionState.Outgoing)
                        DisconnectPeerForce(netPeer, DisconnectReason.InvalidProtocol, 0, null);
                    break;
                case PacketProperty.Disconnect:
                    if (peerFound)
                    {
                        var disconnectResult = netPeer.ProcessDisconnect(packet);
                        if (disconnectResult == DisconnectResult.None)
                        {
                            NetPacketPool.Recycle(packet);
                            return;
                        }
                        DisconnectPeerForce(
                            netPeer, 
                            disconnectResult == DisconnectResult.Disconnect
                            ? DisconnectReason.RemoteConnectionClose
                            : DisconnectReason.ConnectionRejected,
                            0, packet);
                    }
                    else
                    {
                        NetPacketPool.Recycle(packet);
                    }
                    //Send shutdown
                    SendRawAndRecycle(NetPacketPool.GetWithProperty(PacketProperty.ShutdownOk), remoteEndPoint);
                    break;
                case PacketProperty.ConnectAccept:
                    if (!peerFound)
                        return;
                    var connAccept = NetConnectAcceptPacket.FromData(packet);
                    if (connAccept != null && netPeer.ProcessConnectAccept(connAccept))
                        CreateEvent(NetEvent.EType.Connect, netPeer);
                    break;
                default:
                    if(peerFound)
                        netPeer.ProcessPacket(packet);
                    else
                        SendRawAndRecycle(NetPacketPool.GetWithProperty(PacketProperty.PeerNotFound), remoteEndPoint);
                    break;
            }
        }

19 View Source File : NetManager.cs
License : MIT License
Project Creator : nievesj

public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options)
        {
            try
            {
                _peersLock.EnterReadLock();
                for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
                    netPeer.Send(data, start, length, channelNumber, options);
            }
            finally
            {
                _peersLock.ExitReadLock();
            }
        }

19 View Source File : NetManager.cs
License : MIT License
Project Creator : nievesj

public void SendToAll(byte[] data, int start, int length, byte channelNumber, DeliveryMethod options, NetPeer excludePeer)
        {
            try
            {
                _peersLock.EnterReadLock();
                for (var netPeer = _headPeer; netPeer != null; netPeer = netPeer.NextPeer)
                {
                    if (netPeer != excludePeer)
                        netPeer.Send(data, start, length, channelNumber, options);
                }
            }
            finally
            {
                _peersLock.ExitReadLock();
            }
        }

See More Examples