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 : ConcurrentEntityCollection.cs
License : MIT License
Project Creator : SpiceSharp

public virtual IEnumerator<IEnreplacedy> GetEnumerator()
        {
            IEnreplacedy[] result;
            _lock.EnterReadLock();
            try
            {
                result = _enreplacedies.Values.ToArray();
            }
            finally
            {
                _lock.ExitReadLock();
            }

            // Enumerate
            foreach (var enreplacedy in result)
                yield return enreplacedy;
        }

19 View Source File : ConcurrentEntityCollection.cs
License : MIT License
Project Creator : SpiceSharp

public bool Contains(IEnreplacedy item)
        {
            _lock.EnterReadLock();
            try
            {
                if (_enreplacedies.TryGetValue(item.Name, out var result))
                    return result == item;
                return false;
            }
            finally
            {
                _lock.ExitReadLock();
            }
        }

19 View Source File : BehaviorContainerCollection.cs
License : MIT License
Project Creator : SpiceSharp

public virtual bool Contains(string name)
        {
            _lock.EnterReadLock();
            try
            {
                return _dictionary.ContainsKey(name);
            }
            finally
            {
                _lock.ExitReadLock();
            }
        }

19 View Source File : WinFormsGameWindow.cs
License : MIT License
Project Creator : sqrMin1

internal void UpdateWindows()
        {
            _allWindowsReaderWriterLockSlim.EnterReadLock();

            try
            {
                // Update the mouse state for each window.
                foreach (var window in _allWindows)
                    if (window.Game == Game)
                        window.UpdateMouseState();
            }
            finally
            {
                _allWindowsReaderWriterLockSlim.ExitReadLock();
            }
        }

19 View Source File : SessionAcceptorBase.cs
License : GNU General Public License v3.0
Project Creator : starts2000

public ISession GetConnectedSession(ISessionIdMetaData sessionId)
        {
            if(sessionId == null)
            {
                return null;
            }

            _connectedSessionLock.EnterReadLock();

            try
            {
                return _connectedSessions.Values.FirstOrDefault(session =>
                {
                    return sessionId.Equals(session.SessionId);
                });
            }
            finally
            {
                _connectedSessionLock.ExitReadLock();
            }
        }

19 View Source File : SessionAcceptorBase.cs
License : GNU General Public License v3.0
Project Creator : starts2000

public IList<ISession> GetConnectedSessionMetaData(
            Func<ISession, bool> selector)
        {
            _connectedSessionLock.EnterReadLock();

            try
            {
                return _connectedSessions.Values.Where(selector).ToList();
            }
            finally
            {
                _connectedSessionLock.ExitReadLock();
            }
        }

19 View Source File : Main.cs
License : Apache License 2.0
Project Creator : steponteam

private string[] MatchAll(Feature[] features)
        {
            var result = Enumerable.Repeat("陌生人", features.Length).ToArray();

            if (_cache.Count == 0)
                return result;

            //依次处理找到的人脸
            var max = new float[features.Length];

            try
            {
                _cacheLock.EnterReadLock();

                foreach (var single in _cache)
                    for (var i = 0; i < features.Length; i++)
                    {
                        var sim = _processor.Match(features[i].FeatureData,
                            single.Value); //此方法默认保留采集到的特征(非托管内存),并自动释放被比较(特征库)的特征数据,所以无需担心内存泄露
                        if (sim > 0.5)
                            if (sim > max[i])
                            {
                                max[i] = sim;
                                result[i] = single.Key;
                            }
                    }
            }
            finally
            {
                _cacheLock.ExitReadLock();
            }


            return result;
        }

19 View Source File : StatusByLatLonChartView.cs
License : Microsoft Public License
Project Creator : stewienj

protected override BitmapSource RenderFrame(DataRect data, Rect output, RenderRequest renderRequest)
		{
			var transform = Plotter2D?.Viewport?.Transform?.DataTransform;

			// Return null if no update required
			if (_shutdownStarted || data.Width == 0 || data.Height == 0 || _source == null)
			{
				return null;
			}

			_activeRequest = renderRequest;
			try
			{
				_sourceLock.EnterReadLock();

				// Check the nominated source size doesn't exceed the source data size
				if (_sourceWidth * _sourceHeight > _source.Count)
				{
					return null;
				}

				double dataToSourceWidth = (double)_sourceWidth / (double)_renderWidth;
				double dataToSourceHeight = (double)_sourceHeight / (double)_renderHeight;

				int outputWidth = (int)Math.Round(output.Width);
				int outputHeight = (int)Math.Round(output.Height);
				var newPixels = new uint[outputWidth * outputHeight];

				// Mulreplacedhread the rendering
				var yRange = Enumerable.Range(0, outputHeight);

				Batch(yRange, 64).AsParallel().ForAll(yBatch =>
				{
					foreach (int y in yBatch)
					{
						double fractionOfRectY = (double)y / outputHeight;
						double positionY = fractionOfRectY * data.Height + data.YMin;
						if (transform != null)
						{
							if (positionY < transform.MaxLareplacedude && (-positionY) < transform.MaxLareplacedude)
							{
								positionY = transform.ViewportToData(new Point(0, positionY)).Y;
							}
							else
							{
								continue;
							}
						}
						// The Y source coordinate will be ...
						int sourceIndexY = (int)Math.Floor((positionY - _renderMinY) * dataToSourceHeight);
						double pixelWidth = 1.0 / outputWidth;
						if (sourceIndexY >= 0 && sourceIndexY < _sourceHeight)
						{
							int sourceIndexYOffset = _sourceWidth * sourceIndexY;
							int destIndex = (outputHeight - 1 - y) * outputWidth;
							for (int x = 0; x < outputWidth; ++x)
							{
								// Optimise the divide by precalculating the reciprocal
								double fractionOfRectX = x * pixelWidth;
								double positionX = fractionOfRectX * data.Width + data.XMin;
								// The X source coordinate will be ...
								int sourceIndexX = (int)Math.Floor((positionX - _renderMinX) * dataToSourceWidth);
								if (sourceIndexX >= 0 && sourceIndexX < _sourceWidth)
								{
									newPixels[destIndex] = _source[sourceIndexX + sourceIndexYOffset];
								}
								++destIndex;
							}
						}
					}
				});
				var retVal = BitmapSource.Create(outputWidth, outputHeight, 96.0, 96.0, PixelFormats.Bgra32, null, newPixels, outputWidth * 4);
				retVal.Freeze();
				return retVal;
			}
			catch (Exception)
			{
				return null;
			}
			finally
			{
				_sourceLock.ExitReadLock();
				_activeRequest = null;
			}
		}

19 View Source File : ReaderWriterLock.cs
License : MIT License
Project Creator : stratisproject

public IDisposable LockRead()
        {
            return new ActionDisposable(() => @lock.EnterReadLock(), () => @lock.ExitReadLock());
        }

19 View Source File : ReaderWriterLock.cs
License : MIT License
Project Creator : stratisproject

public IDisposable LockRead()
        {
            return new ActionDisposable(() => this.rwLock.EnterReadLock(), () => this.rwLock.ExitReadLock());
        }

19 View Source File : SerializerFactorySelector.cs
License : MIT License
Project Creator : stride3d

public IYamlSerializable GetSerializer(SerializerContext context, ITypeDescriptor typeDescriptor)
        {
            if (!isSealed) throw new InvalidOperationException("A serializer factory selector must be sealed before being used.");
            IYamlSerializable serializer;

            // First try, with just a read lock
            serializerLock.EnterReadLock();
            var found = serializers.TryGetValue(typeDescriptor.Type, out serializer);
            serializerLock.ExitReadLock();

            if (!found)
            {
                // Not found, let's take exclusive lock and try again
                serializerLock.EnterWriteLock();
                if (!serializers.TryGetValue(typeDescriptor.Type, out serializer))
                {
                    foreach (var factory in factories)
                    {
                        serializer = factory.TryCreate(context, typeDescriptor);
                        if (serializer != null)
                        {
                            serializers.Add(typeDescriptor.Type, serializer);
                            break;
                        }
                    }
                }
                serializerLock.ExitWriteLock();
            }

            if (serializer == null)
            {
                throw new InvalidOperationException($"Unable to find a serializer for the type [{typeDescriptor.Type}]");
            }

            return serializer;
        }

19 View Source File : SparseClusteredArray.cs
License : MIT License
Project Creator : supermemo

internal (int, List<Segment>) AcquireReadLock(Func<List<Segment>, (int, List<Segment>)> filterFunc)
    {
      List<Segment> localSegs = new List<Segment>(Segments.Count + 2);

      do
      {
        Lock.EnterReadLock();

        try
        {
          localSegs.AddRange(Segments);
        }
        finally
        {
          Lock.ExitReadLock();
        }

        int idxArr = 0;

        // Wrap in try/finally ?
        for (; idxArr < localSegs.Count; idxArr++)
        {
          Segment seg = localSegs[idxArr];

          seg.Lock.EnterReadLock();

          if (seg.Inconsistent)
            break;
        }

        if (idxArr < localSegs.Count)
        {
          for (idxArr = idxArr - 1; idxArr >= 0; idxArr--)
            localSegs[idxArr].Lock.ExitReadLock();

          localSegs.Clear();

          Thread.Yield();
          continue;
        }
        // !Wrap in try/finally ?


        (int ret, List<Segment> filteredSegs) = filterFunc(localSegs);

        foreach (var seg in localSegs.Except(filteredSegs))
          seg.Lock.ExitReadLock();

        return (ret, filteredSegs);
      } while (true);
    }

19 View Source File : AtomFeedHelper.cs
License : MIT License
Project Creator : sverrirs

public static SyndicationFeed LoadAtomFeed(string atomFeedFilePath)
        {
            // Wait until the feed file has been released by other processes before attempting to read
            atomFeedLock.EnterReadLock();
            try
            {
                using (var stream = File.OpenRead(atomFeedFilePath))
                using (var reader = XmlReader.Create(stream))
                {
                    return SyndicationFeed.Load(reader);
                }
            }
            catch
            {
                return null;
            }
            finally
            {
                atomFeedLock.ExitReadLock();
            }
        }

19 View Source File : FileCounter.cs
License : MIT License
Project Creator : sverrirs

public static int GetDownloadCount(string vsixId, IStorageConfiguration configuration)
        {
            downloadCountFileLock.EnterReadLock();
            try
            {
                return CoreGetDownloadCount(vsixId, configuration);
            }
            finally
            {
                downloadCountFileLock.ExitReadLock();
            }
        }

19 View Source File : FileCounter.cs
License : MIT License
Project Creator : sverrirs

public static string GetVsixFileFromId(string vsixId, IStorageConfiguration configuration)
        {
            vsixInfoFileLock.EnterReadLock();
            try
            {
                string vsixMarkPath = Path.Combine(Environment.CurrentDirectory, configuration.VsixStorageDirectory, "VSIXData", vsixId, "info.txt");

                if (!File.Exists(vsixMarkPath))
                    return null;

                var fileName = File.ReadAllText(vsixMarkPath);
                return Path.Combine(Environment.CurrentDirectory, configuration.VsixStorageDirectory, fileName);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }
            finally
            {
                vsixInfoFileLock.ExitReadLock();
            }
        }

19 View Source File : FileCounter.cs
License : MIT License
Project Creator : sverrirs

public static Tuple<float, int> GetRating(string vsixId, IStorageConfiguration configuration)
        {
            ratingsFileLock.EnterReadLock();
            try
            {
                return CoreGetRating(vsixId, configuration);
            }
            finally
            {
                ratingsFileLock.ExitReadLock();
            }
        }

19 View Source File : GuidLookup.cs
License : MIT License
Project Creator : szszss

public static bool GetGuid(string name, out Guid result)
		{
			readWriteLock.EnterReadLock();
			try
			{
				return strToGuid.TryGetValue(name, out result);
			}
			finally
			{
				readWriteLock.ExitReadLock();
			}
		}

19 View Source File : GuidLookup.cs
License : MIT License
Project Creator : szszss

public static bool GetName(Guid guid, out string result)
		{
			result = null;
			readWriteLock.EnterReadLock();
			try
			{
				return guidToStr.TryGetValue(guid, out result);
			}
			finally
			{
				readWriteLock.ExitReadLock();
			}
		}

19 View Source File : AssetCache.cs
License : MIT License
Project Creator : tagcode

public LineResourceStream GetResourceStream(ILine key)
        {
            Cache _cache = this.cache;

            // Try to read previously cached value
            LineResourceBytes value = default;
            _cache.m_lock.EnterReadLock();
            try
            {
                if (_cache.data.TryGetValue(key, out value))
                {
                    if (value.Value!=null)
                        return new LineResourceStream(value.Line, value.Value == null ? null : new MemoryStream(value.Value), value.Exception, value.Status);
                }
            }
            finally
            {
                _cache.m_lock.ExitReadLock();
            }

            // Open stream
            LineResourceStream stream = Source.GetResourceStream(key);

            // Store into cache?
            if (Options.GetCacheStreams())
            {
                ILine cacheKey = Options.GetCloneKeys() ? key.CloneKey(LineAppender.NonResolving) : key;

                // Cache null value
                if (stream.Value == null)
                {
                    _cache.m_lock.EnterWriteLock();
                    try
                    {
                        _cache.data[cacheKey] = new LineResourceBytes(value.Line, value.Exception, value.Status);
                        return stream;
                    }
                    finally
                    {
                        _cache.m_lock.ExitWriteLock();
                    }
                }

                // Read stream completely and then cache it
                long position = -1;
                int ix = 0;
                try
                {
                    // Try to read stream length, if fails, throws an exception
                    long len = stream.Value.Length;

                    if (len < Options.GetMaxResourceSize())
                    {
                        // Try to read position.
                        position = stream.Value.Position;

                        // Try to read stream completely.
                        int len_ = (int)len;
                        byte[] data = new byte[len];

                        // Read chunks
                        while (ix < len_)
                        {
                            int count = stream.Value.Read(data, ix, len_ - ix);

                            // 
                            // "returns zero (0) if the end of the stream has been reached."
                            //     
                            if (count == 0) break;

                            ix += count;
                        }

                        // Write data to cache
                        if (ix == len_)
                        {
                            _cache.m_lock.EnterWriteLock();
                            try
                            {
                                _cache.data[cacheKey] = new LineResourceBytes(value.Line, data, value.Status);
                                // Wrap to new stream.
                                return new LineResourceStream(value.Line, new MemoryStream(data), value.Status);
                            }
                            finally
                            {
                                _cache.m_lock.ExitWriteLock();
                            }
                        }
                        else
                        {
                            // Reading completely failed, revert position
                            stream.Value.Position = position;
                            ix = 0;
                        }
                    }
                }
                catch (Exception)
                {
                    try
                    {
                        // Return position. 
                        if (position > 0L) { stream.Value.Position = position; ix = 0; }
                    }
                    catch (Exception)
                    {
                        // Failed to rewind stream.
                    }

                    // Stream has not been rewound. Let's open it again.
                    if (ix > 0)
                    {
                        stream.Value.Dispose();
                        return Source.GetResourceStream(key);
                    }
                }
            }
            return new LineResourceStream(key, (Exception)null, LineStatus.ResolveFailedNoResult);
        }

19 View Source File : AssetCache.cs
License : MIT License
Project Creator : tagcode

public ILine GetLine(ILine key)
        {
            Cache _cache = this.cache;

            // Try to read previously cached value
            ILine value = null;
            _cache.m_lock.EnterReadLock();
            try
            {
                if (_cache.strings.TryGetValue(key, out value)) return value;
            }
            finally
            {
                _cache.m_lock.ExitReadLock();
            }

            // Read from backend and write to cache
            value = Source.GetLine(key);

            // Write to cache, be that null or not
            ILine cacheKey = key.CloneKey(LineAppender.NonResolving);
            _cache.m_lock.EnterWriteLock();
            try
            {
                _cache.strings[cacheKey] = value;
            }
            finally
            {
                _cache.m_lock.ExitWriteLock();
            }

            return value;
        }

19 View Source File : AssetCache.cs
License : MIT License
Project Creator : tagcode

public LineResourceBytes GetResourceBytes(ILine key)
        {
            Cache _cache = this.cache;

            // Try to read previously cached value
            LineResourceBytes value = default;
            _cache.m_lock.EnterReadLock();
            try
            {
                if (_cache.data.TryGetValue(key, out value)) return value;
            }
            finally
            {
                _cache.m_lock.ExitReadLock();
            }

            // Read from backend and write to cache
            value = Source.GetResourceBytes(key);

            // Write to cache, be that null or not
            if (value.Value != null && value.Value.Length <= Options.GetMaxResourceSize())
            {
                ILine cacheKey = key.CloneKey(LineAppender.NonResolving);
                _cache.m_lock.EnterWriteLock();
                try
                {
                    _cache.data[cacheKey] = value;
                }
                finally
                {
                    _cache.m_lock.ExitWriteLock();
                }
            }

            return value;
        }

19 View Source File : ReaderWriterCache.cs
License : Apache License 2.0
Project Creator : TANZAME

public virtual TValue GetOrAdd(TKey key, Func<TKey, TValue> creator = null)
        {
            // <<<<<<<<< 尝试在不加锁的情况下读取记录 >>>>>>>>>>>
            TValue obj;
            if (this._innerCache.TryGetValue(key, out obj))
                return obj;

            try
            {
                this._rwLock.EnterReadLock();
                if (this._innerCache.TryGetValue(key, out obj)) 
                    return obj;
            }
            finally
            {
                this._rwLock.ExitReadLock();
            }

            if (creator == null) 
                return default(TValue);

            try
            {
                this._rwLock.EnterWriteLock();
                TValue obj1;
                if (this._innerCache.TryGetValue(key, out obj1)) 
                    return obj1;
                
                TValue obj2 = creator(key);
                this._innerCache[key] = obj2;
                return obj2;
            }
            finally
            {
                this._rwLock.ExitWriteLock();
            }
        }

19 View Source File : ReaderWriterCache.cs
License : Apache License 2.0
Project Creator : TANZAME

public virtual bool TryGet(TKey key, out TValue value)
        {
            this._rwLock.EnterReadLock();
            try
            {
                if (this._innerCache.TryGetValue(key, out value))
                    return true;
            }
            finally
            {
                this._rwLock.ExitReadLock();
            }
            return false;
        }

19 View Source File : Startup.cs
License : GNU General Public License v3.0
Project Creator : TechnitiumSoftware

public void Configure(IApplicationBuilder app, IHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await Task.Run(() =>
                {
                    if (context.Request.Path == "/connectivity/")
                    {
                        if (!ushort.TryParse(context.Request.Query["port"], out ushort port))
                        {
                            context.Response.StatusCode = 400;
                            return;
                        }

                        IPEndPoint remoteEP = new IPEndPoint(GetRequestRemoteAddress(context), port);
                        bool success = false;

                        try
                        {
                            using (Socket socket = new Socket(remoteEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
                            {
                                IAsyncResult result = socket.BeginConnect(remoteEP, null, null);
                                if (!result.AsyncWaitHandle.WaitOne(CONNECTION_TIMEOUT))
                                    throw new SocketException((int)SocketError.TimedOut);

                                socket.NoDelay = true;
                                socket.SendTimeout = SOCKET_SEND_TIMEOUT;
                                socket.ReceiveTimeout = SOCKET_RECV_TIMEOUT;

                                MakeDecoyHttpConnection(new NetworkStream(socket), remoteEP);

                                success = true;
                            }
                        }
                        catch
                        { }

                        List<IPEndPoint> peerEPs = new List<IPEndPoint>();
                        bool add;

                        _openPeerEPsLock.EnterReadLock();
                        try
                        {
                            add = (_openPeerEPs.Count < MAX_PEER_ENDPOINTS);

                            foreach (PeerEndPoint peerEP in _openPeerEPs)
                            {
                                if (remoteEP.Equals(peerEP.EndPoint))
                                {
                                    add = false;

                                    if (success)
                                        peerEP.AddedOn = DateTime.UtcNow;
                                }
                                else
                                {
                                    peerEPs.Add(peerEP.EndPoint);
                                }
                            }
                        }
                        finally
                        {
                            _openPeerEPsLock.ExitReadLock();
                        }

                        if (add)
                        {
                            _openPeerEPsLock.EnterWriteLock();
                            try
                            {
                                if (_openPeerEPs.Count < MAX_PEER_ENDPOINTS)
                                    _openPeerEPs.Add(new PeerEndPoint(remoteEP));
                            }
                            finally
                            {
                                _openPeerEPsLock.ExitWriteLock();
                            }
                        }

                        context.Response.ContentType = "application/octet-stream";

                        using (MemoryStream mS = new MemoryStream(20))
                        {
                            BinaryWriter bW = new BinaryWriter(mS);

                            bW.Write((byte)1); //version
                            bW.Write(success); //test status
                            remoteEP.WriteTo(bW); //self end-point

                            //write peers
                            bW.Write(Convert.ToByte(peerEPs.Count));
                            foreach (IPEndPoint peerEP in peerEPs)
                                peerEP.WriteTo(bW);

                            byte[] output = mS.ToArray();

                            context.Response.Headers.Add("Content-Length", output.Length.ToString());

                            using (context.Response.Body)
                            {
                                context.Response.Body.WriteAsync(output, 0, output.Length);
                            }
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = 404;
                    }
                });
            });
        }

19 View Source File : LocalChunkColumn.cs
License : MIT License
Project Creator : TechnologicalPizza

public bool ContainsChunk(int chunkY)
        {
            _chunkLock.EnterReadLock();
            try
            {
                return _chunks.ContainsKey(chunkY);
            }
            finally
            {
                _chunkLock.ExitReadLock();
            }
        }

19 View Source File : LocalChunkColumn.cs
License : MIT License
Project Creator : TechnologicalPizza

public ValueTask<IChunk> GetOrAddChunk(int chunkY)
        {
            _chunkLock.EnterReadLock();
            try
            {
                if (_chunks.TryGetValue(chunkY, out LocalChunk? chunk))
                    return new ValueTask<IChunk>(chunk);
            }
            finally
            {
                _chunkLock.ExitReadLock();
            }

            _chunkLock.EnterUpgradeableReadLock();
            try
            {
                if (_chunks.TryGetValue(chunkY, out LocalChunk? chunk))
                    return new ValueTask<IChunk>(chunk);

                ChunkPosition position = new(Position, chunkY);

                ValueTask<IChunk> getTask = ColumnManager.ChunkProvider.GetOrAddChunk(ColumnManager, position);
                if (getTask.IsCompleted)
                {
                    LoadChunkContinuation(getTask.Result, this);
                    return getTask;
                }

                Task<IChunk> loadTask = getTask.AsTask().ContinueWith(
                    (t, s) => LoadChunkContinuation(t.Result, s), this, TaskContinuationOptions.ExecuteSynchronously);
                return new ValueTask<IChunk>(loadTask);
            }
            finally
            {
                _chunkLock.ExitUpgradeableReadLock();
            }
        }

19 View Source File : LocalChunkColumnProvider.cs
License : MIT License
Project Creator : TechnologicalPizza

public ValueTask<IChunkColumn?> RemoveChunkColumn(ChunkColumnPosition columnPosition)
        {
            _columnLock.EnterReadLock();
            try
            {
                if (TryRemoveColumn(columnPosition, out ValueTask<IChunkColumn?> task))
                    return task;
            }
            finally
            {
                _columnLock.ExitReadLock();
            }

            _columnLock.EnterUpgradeableReadLock();
            try
            {
                if (TryRemoveColumn(columnPosition, out ValueTask<IChunkColumn?> task))
                    return task;

                Task<IChunkColumn?> unloadTask = UnloadColumn(columnPosition)
                    .ContinueWith((finishedTask) =>
                {
                    _columnLock.EnterWriteLock();
                    try
                    {
                        _columns.Remove(columnPosition);
                        _unloadingColumns.Remove(columnPosition);

                        IChunkColumn? result = finishedTask.Result;
                        if (result != null)
                            ChunkRemoved?.Invoke(this, result);
                        return result;
                    }
                    finally
                    {
                        _columnLock.ExitWriteLock();
                    }
                }, TaskContinuationOptions.ExecuteSynchronously);

                if (!unloadTask.IsCompleted)
                {
                    _columnLock.EnterWriteLock();
                    try
                    {
                        _unloadingColumns.Add(columnPosition, unloadTask);
                    }
                    finally
                    {
                        _columnLock.ExitWriteLock();
                    }
                }
                return new ValueTask<IChunkColumn?>(unloadTask);
            }
            finally
            {
                _columnLock.ExitUpgradeableReadLock();
            }
        }

19 View Source File : LocalChunkColumnProvider.cs
License : MIT License
Project Creator : TechnologicalPizza

public ValueTask<ChunkStatus> GetChunkColumnStatus(ChunkColumnPosition columnPosition)
        {
            _columnLock.EnterReadLock();
            try
            {
                if (_columns.ContainsKey(columnPosition))
                    return new ValueTask<ChunkStatus>(ChunkStatus.Loaded);

                if (_loadingColumns.ContainsKey(columnPosition))
                    return new ValueTask<ChunkStatus>(ChunkStatus.InQueue);
            }
            finally
            {
                _columnLock.ExitReadLock();
            }
            return new ValueTask<ChunkStatus>(ChunkStatus.Unloaded);
        }

19 View Source File : LocalChunkColumnProvider.cs
License : MIT License
Project Creator : TechnologicalPizza

public ValueTask<IChunkColumn> GetOrAddChunkColumn(ChunkColumnManager columnManager, ChunkColumnPosition columnPosition)
        {
            _columnLock.EnterReadLock();
            try
            {
                if (TryGetColumn(columnPosition, out ValueTask<IChunkColumn> task))
                    return task;
            }
            finally
            {
                _columnLock.ExitReadLock();
            }

            // Only one thread can enter an upgradeable lock.
            _columnLock.EnterUpgradeableReadLock();
            try
            {
                if (TryGetColumn(columnPosition, out ValueTask<IChunkColumn> task))
                    return task;

                Task<IChunkColumn> loadTask = LoadOrGenerateColumn(columnManager, columnPosition);
                Task continuation = loadTask.ContinueWith(static (finishedTask, self) =>
                {
                    var t = Unsafe.As<LocalChunkColumnProvider>(self)!;
                    IChunkColumn result = finishedTask.Result;
                    t._columnLock.EnterWriteLock();
                    try
                    {
                        t._columns.Add(result.Position, result);
                        t._loadingColumns.Remove(result.Position);
                        t.ChunkAdded?.Invoke(t, result);
                    }
                    finally
                    {
                        t._columnLock.ExitWriteLock();
                    }
                }, this, TaskContinuationOptions.ExecuteSynchronously);

                if (!continuation.IsCompleted)
                {
                    _columnLock.EnterWriteLock();
                    try
                    {
                        _loadingColumns.Add(columnPosition, loadTask);
                    }
                    finally
                    {
                        _columnLock.ExitWriteLock();
                    }
                }
                return new ValueTask<IChunkColumn>(loadTask);
            }
            finally
            {
                _columnLock.ExitUpgradeableReadLock();
            }
        }

19 View Source File : LocalChunkColumnProvider.cs
License : MIT License
Project Creator : TechnologicalPizza

public bool TryGetChunkColumn(ChunkColumnPosition columnPosition, [MaybeNullWhen(false)] out IChunkColumn chunkColumn)
        {
            _columnLock.EnterReadLock();
            try
            {
                if (_columns.TryGetValue(columnPosition, out IChunkColumn? column))
                {
                    chunkColumn = column;
                    return true;
                }
                chunkColumn = default;
                return false;
            }
            finally
            {
                _columnLock.ExitReadLock();
            }
        }

19 View Source File : LocalChunkColumnProvider.cs
License : MIT License
Project Creator : TechnologicalPizza

private ValueTask<IChunkRegion> GetRegion(ChunkRegionPosition regionPosition)
        {
            _regionLock.EnterReadLock();
            try
            {
                if (TryGetRegion(regionPosition, out ValueTask<IChunkRegion> task))
                    return task;
            }
            finally
            {
                _regionLock.ExitReadLock();
            }

            // Only one thread can enter an upgradeable lock.
            _regionLock.EnterUpgradeableReadLock();
            try
            {
                if (TryGetRegion(regionPosition, out ValueTask<IChunkRegion> task))
                    return task;

                Task<IChunkRegion> loadTask = LoadRegion(regionPosition);
                Task continuation = loadTask.ContinueWith((finishedTask) =>
                {
                    IChunkRegion result = finishedTask.Result;
                    _regionLock.EnterWriteLock();
                    try
                    {
                        _regions.Add(regionPosition, result);
                        _loadingRegions.Remove(regionPosition);
                        //RegionAdded?.Invoke(this, result); // TODO
                    }
                    finally
                    {
                        _regionLock.ExitWriteLock();
                    }
                }, TaskContinuationOptions.ExecuteSynchronously);

                if (!continuation.IsCompleted)
                {
                    _regionLock.EnterWriteLock();
                    try
                    {
                        _loadingRegions.Add(regionPosition, loadTask);
                    }
                    finally
                    {
                        _regionLock.ExitWriteLock();
                    }
                }
                return new ValueTask<IChunkRegion>(loadTask);
            }
            finally
            {
                _regionLock.ExitUpgradeableReadLock();
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : telerik

private static void AttachEventListeners()
        {
            //
            // It is important to understand that FiddlerCore calls event handlers on session-handling
            // background threads.  If you need to properly synchronize to the UI-thread (say, because
            // you're adding the sessions to a list view) you must call .Invoke on a delegate on the 
            // window handle.
            // 
            // If you are writing to a non-threadsafe data structure (e.g. List<T>) you must
            // use a Monitor or other mechanism to ensure safety.
            //

            // Simply echo notifications to the console.  Because Fiddler.CONFIG.QuietMode=true 
            // by default, we must handle notifying the user ourselves.
            FiddlerApplication.OnNotification += (o, nea) => Console.WriteLine($"** NotifyUser: {nea.NotifyString}");

            FiddlerApplication.Log.OnLogString += (o, lea) => Console.WriteLine($"** LogString: {lea.LogString}");

            FiddlerApplication.BeforeRequest += session =>
            {
                // In order to enable response tampering, buffering mode MUST
                // be enabled; this allows FiddlerCore to permit modification of
                // the response in the BeforeResponse handler rather than streaming
                // the response to the client as the response comes in.
                session.bBufferResponse = false;

                // Set this property if you want FiddlerCore to automatically authenticate by
                // answering Digest/Negotiate/NTLM/Kerberos challenges itself
                // session["X-AutoAuth"] = "(default)";

                try
                {
                    sessionsLock.EnterWriteLock();
                    sessions.Add(session);
                }
                finally
                {
                    sessionsLock.ExitWriteLock();
                }
            };

            /*
            // The following event allows you to examine every response buffer read by Fiddler. Note that this isn't useful for the vast majority of
            // applications because the raw buffer is nearly useless; it's not decompressed, it includes both headers and body bytes, etc.
            //
            // This event is only useful for a handful of applications which need access to a raw, unprocessed byte-stream
            Fiddler.FiddlerApplication.OnReadResponseBuffer += (o, rrea) =>
            {
                // NOTE: arrDataBuffer is a fixed-size array. Only bytes 0 to iCountOfBytes should be read/manipulated.
                //
                // Just for kicks, lowercase every byte. Note that this will obviously break any binary content.
                for (int i = 0; i < e.iCountOfBytes; i++)
                {
                    if ((e.arrDataBuffer[i] > 0x40) && (e.arrDataBuffer[i] < 0x5b))
                    {
                        e.arrDataBuffer[i] = (byte)(e.arrDataBuffer[i] + (byte)0x20);
                    }
                }
                Console.WriteLine(String.Format("Read {0} response bytes for session {1}", e.iCountOfBytes, e.sessionOwner.id));
            }
            */

            /*
            Fiddler.FiddlerApplication.BeforeResponse += session => {
                // Console.WriteLine($"{session.id}:HTTP {session.responseCode} for {session.fullUrl}");

                // Uncomment the following two statements to decompress/unchunk the
                // HTTP response and subsequently modify any HTTP responses to replace 
                // instances of the word "Telerik" with "Progress". You MUST also
                // set session.bBufferResponse = true inside the BeforeRequest event handler above.
                //
                //session.utilDecodeResponse(); session.utilReplaceInResponse("Telerik", "Progress");
            };*/

            FiddlerApplication.AfterSessionComplete += session =>
            {
                //Console.WriteLine($"Finished session: {oS.fullUrl}");

                int sessionsCount = 0;
                try
                {
                    sessionsLock.EnterReadLock();
                    sessionsCount = sessions.Count;
                }
                finally
                {
                    sessionsLock.ExitReadLock();
                }

                if (sessionsCount == 0)
                    return;

                Console.replacedle = $"Session list contains: {sessionsCount} sessions";
            };

            // Tell the system console to handle CTRL+C by calling our method that
            // gracefully shuts down the FiddlerCore.
            //
            // Note, this doesn't handle the case where the user closes the window with the close button.
            Console.CancelKeyPress += (o, ccea) =>
            {
                Quit();
            };
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : telerik

private static void WriteSessions(IEnumerable<Session> sessions)
        {
            ConsoleColor oldColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.White;
            StringBuilder sb = new StringBuilder($"Session list contains:{Environment.NewLine}");
            try
            {
                sessionsLock.EnterReadLock();
                foreach (Session s in sessions)
                {
                    sb.AppendLine($"{s.id} {s.oRequest.headers.HTTPMethod} {Ellipsize(s.fullUrl, 60)}");
                    sb.AppendLine($"{s.responseCode} {s.oResponse.MIMEType}{Environment.NewLine}");
                }
            }
            finally
            {
                sessionsLock.ExitReadLock();
            }

            Console.Write(sb.ToString());
            Console.ForegroundColor = oldColor;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : telerik

private static void AttachEventListeners()
        {
            //
            // It is important to understand that FiddlerCore calls event handlers on session-handling
            // background threads.  If you need to properly synchronize to the UI-thread (say, because
            // you're adding the sessions to a list view) you must call .Invoke on a delegate on the 
            // window handle.
            // 
            // If you are writing to a non-threadsafe data structure (e.g. List<T>) you must
            // use a Monitor or other mechanism to ensure safety.
            //

            FiddlerApplication.Log.OnLogString += (o, lea) => Console.WriteLine($"** LogString: {lea.LogString}");

            FiddlerApplication.BeforeRequest += session =>
            {
                // In order to enable response tampering, buffering mode MUST
                // be enabled; this allows FiddlerCore to permit modification of
                // the response in the BeforeResponse handler rather than streaming
                // the response to the client as the response comes in.
                session.bBufferResponse = false;

                // Set this property if you want FiddlerCore to automatically authenticate by
                // answering Digest/Negotiate/NTLM/Kerberos challenges itself
                // session["X-AutoAuth"] = "(default)";

                try
                {
                    sessionsLock.EnterWriteLock();
                    sessions.Add(session);
                }
                finally
                {
                    sessionsLock.ExitWriteLock();
                }
            };

            /*
            // The following event allows you to examine every response buffer read by Fiddler. Note that this isn't useful for the vast majority of
            // applications because the raw buffer is nearly useless; it's not decompressed, it includes both headers and body bytes, etc.
            //
            // This event is only useful for a handful of applications which need access to a raw, unprocessed byte-stream
            Fiddler.FiddlerApplication.OnReadResponseBuffer += (o, rrea) =>
            {
                // NOTE: arrDataBuffer is a fixed-size array. Only bytes 0 to iCountOfBytes should be read/manipulated.
                //
                // Just for kicks, lowercase every byte. Note that this will obviously break any binary content.
                for (int i = 0; i < e.iCountOfBytes; i++)
                {
                    if ((e.arrDataBuffer[i] > 0x40) && (e.arrDataBuffer[i] < 0x5b))
                    {
                        e.arrDataBuffer[i] = (byte)(e.arrDataBuffer[i] + (byte)0x20);
                    }
                }
                Console.WriteLine(String.Format("Read {0} response bytes for session {1}", e.iCountOfBytes, e.sessionOwner.id));
            }
            */

            /*
            Fiddler.FiddlerApplication.BeforeResponse += session => {
                // Console.WriteLine($"{session.id}:HTTP {session.responseCode} for {session.fullUrl}");

                // Uncomment the following two statements to decompress/unchunk the
                // HTTP response and subsequently modify any HTTP responses to replace 
                // instances of the word "Telerik" with "Progress". You MUST also
                // set session.bBufferResponse = true inside the BeforeRequest event handler above.
                //
                //session.utilDecodeResponse(); session.utilReplaceInResponse("Telerik", "Progress");
            };*/

            FiddlerApplication.AfterSessionComplete += session =>
            {
                //Console.WriteLine($"Finished session: {oS.fullUrl}");

                int sessionsCount = 0;
                try
                {
                    sessionsLock.EnterReadLock();
                    sessionsCount = sessions.Count;
                }
                finally
                {
                    sessionsLock.ExitReadLock();
                }

                if (sessionsCount == 0)
                    return;

                Console.replacedle = $"Session list contains: {sessionsCount} sessions";
            };

            // Tell the system console to handle CTRL+C by calling our method that
            // gracefully shuts down the FiddlerCore.
            //
            // Note, this doesn't handle the case where the user closes the window with the close button.
            Console.CancelKeyPress += (o, ccea) =>
            {
                Quit();
            };
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : telerik

private static void SaveSessionsToDesktop(IEnumerable<Session> sessions, string preplacedword)
        {
            string filename = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) +
                Path.DirectorySeparatorChar + DateTime.Now.ToString("hh-mm-ss") + ".saz";

            string response;
            try
            {
                sessionsLock.EnterReadLock();
                if (sessions.Any())
                {
                    bool success = Utilities.WriteSessionArchive(filename, sessions.ToArray(), preplacedword);
                    response = $"{(success ? "Wrote" : "Failed to save")}: {filename}";
                }
                else
                {
                    response = "No sessions have been captured.";
                }
            }
            catch (Exception ex)
            {
                response = $"Save failed: {ex.Message}";
            }
            finally
            {
                sessionsLock.ExitReadLock();
            }

            WriteCommandResponse(response);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : telerik

private static void ExecuteUserCommands()
        {
            bool done = false;
            do
            {
                Console.WriteLine("Enter a command [C=Clear; L=List; W=write SAZ; R=read SAZ; Q=Quit]:");
                Console.Write(">");
                ConsoleKeyInfo cki = Console.ReadKey();
                Console.WriteLine();
                switch (char.ToLower(cki.KeyChar))
                {
                    case 'c':
                        try
                        {
                            sessionsLock.EnterWriteLock();
                            sessions.Clear();
                        }
                        finally
                        {
                            sessionsLock.ExitWriteLock();
                        }

                        Console.replacedle = $"Session list contains: 0 sessions";

                        WriteCommandResponse("Clear...");
                        FiddlerApplication.Log.LogString("Cleared session list.");
                        break;

                    case 'l':
                        WriteSessions(sessions);
                        break;

                    case 'w':
                        string preplacedword = null;
                        Console.WriteLine("Preplacedword Protect this Archive (Y/N)?");
                        ConsoleKeyInfo yesNo = Console.ReadKey();
                        if ((yesNo.KeyChar == 'y') || (yesNo.KeyChar == 'Y'))
                        {
                            Console.WriteLine($"{Environment.NewLine}Enter the preplacedword:");
                            preplacedword = Console.ReadLine();
                        }

                        Console.WriteLine();

                        SaveSessionsToDesktop(sessions, preplacedword);
                        break;

                    case 'r':
                        ReadSessions(sessions);

                        int sessionsCount;
                        try
                        {
                            sessionsLock.EnterReadLock();
                            sessionsCount = sessions.Count;
                        }
                        finally
                        {
                            sessionsLock.ExitReadLock();
                        }

                        Console.replacedle = $"Session list contains: {sessionsCount} sessions";

                        break;

                    case 'q':
                        done = true;
                        break;
                }
            } while (!done);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : telerik

private static void SaveSessionsToDesktop(IEnumerable<Session> sessions, string preplacedword)
        {
            string filename = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) +
                Path.DirectorySeparatorChar + DateTime.Now.ToString("hh-mm-ss") + ".saz";

            string response;
            try
            {
                sessionsLock.EnterReadLock();
                if (sessions.Any())
                {
                    bool success = Utilities.WriteSessionArchive(filename, sessions.ToArray(), preplacedword, false);
                    response = $"{(success ? "Wrote" : "Failed to save")}: {filename}";
                }
                else
                {
                    response = "No sessions have been captured.";
                }
            }
            catch (Exception ex)
            {
                response = $"Save failed: {ex.Message}";
            }
            finally
            {
                sessionsLock.ExitReadLock();
            }

            WriteCommandResponse(response);
        }

19 View Source File : AntiDupQueue.cs
License : MIT License
Project Creator : toolgood

private bool tryGet(TKey key, ref TValue value, ref long lastTicks, int secord = 0)
        {
            if (secord == 0) {
                _lock.EnterReadLock();
            } else {
                _lock.TryEnterReadLock(secord * _thousand);
            }
            try {
                if (_map.TryGetValue(key, out value)) {
                    return true;
                }
                lastTicks = _lastTicks;
            } finally { _lock.ExitReadLock(); }
            return false;
        }

19 View Source File : AntiDupQueue.cs
License : MIT License
Project Creator : toolgood

private bool checkGet(TKey key, long lastTicks, ref TValue value, int secord = 0)
        {
            if (secord == 0) {
                _lock.EnterReadLock();
            } else {
                _lock.TryEnterReadLock(secord * _thousand);
            }
            try {
                if (_lastTicks != lastTicks && _map.TryGetValue(key, out value)) {
                    return true;
                }
            } finally { _lock.ExitReadLock(); }
            return false;
        }

19 View Source File : AntiDupCache.cs
License : MIT License
Project Creator : toolgood

private bool tryGet(TKey key, ref TValue value, ref long lastTicks, int secord = 0)
        {
            Tuple<long, TValue> tuple;
            if (secord == 0) {
                _lock.EnterReadLock();
            } else {
                _lock.TryEnterReadLock(secord * _thousand);
            }
            try {
                if (_map.TryGetValue(key, out tuple)) {
                    if (_expireTicks == -1) {
                        value = tuple.Item2;
                        return true;
                    }
                    if (tuple.Item1 + _expireTicks > DateTime.Now.Ticks) {
                        value = tuple.Item2;
                        return true;
                    }
                }
                lastTicks = _lastTicks;
            } finally { _lock.ExitReadLock(); }
            return false;
        }

19 View Source File : AntiDupCache.cs
License : MIT License
Project Creator : toolgood

private bool checkGet(TKey key, long lastTicks, ref TValue value, int secord = 0)
        {
            Tuple<long, TValue> tuple;
            if (secord == 0) {
                _lock.EnterReadLock();
            } else {
                _lock.TryEnterReadLock(secord * _thousand);
            }
            try {
                if (_lastTicks != lastTicks && _map.TryGetValue(key, out tuple)) {
                    if (_expireTicks == -1) {
                        value = tuple.Item2;
                        return true;
                    }
                    if (tuple.Item1 + _expireTicks > DateTime.Now.Ticks) {
                        value = tuple.Item2;
                        return true;
                    }
                }
            } finally { _lock.ExitReadLock(); }
            return false;
        }

19 View Source File : AntiDupCache.cs
License : MIT License
Project Creator : toolgood

private bool containsKey(TKey key, int secord = 0)
        {
            if (secord == 0) {
                _lock.EnterReadLock();
            } else {
                _lock.TryEnterReadLock(secord * _thousand);
            }
            try {
                Tuple<long, TValue> tuple;
                if (_map.TryGetValue(key, out tuple)) {
                    if (_expireTicks == -1) {
                        return true;
                    }
                    if (tuple.Item1 + _expireTicks > DateTime.Now.Ticks) {
                        return true;
                    }
                }

            } finally { _lock.ExitReadLock(); }
            return false;
        }

19 View Source File : AntiDupQueue.cs
License : MIT License
Project Creator : toolgood

private bool containsKey(TKey key, int secord = 0)
        {
            if (secord == 0) {
                _lock.EnterReadLock();
            } else {
                _lock.TryEnterReadLock(secord * _thousand);
            }
            try {
                return _map.ContainsKey(key);
            } finally { _lock.ExitReadLock(); }
        }

19 View Source File : Cache.cs
License : MIT License
Project Creator : toolgood

public TValue Execute(TKey key, Func<TValue> factory)
        {
            // Check cache
            _lock.EnterReadLock();
            TValue val;
            try {
                if (_map.TryGetValue(key, out val))
                    return val;
            } finally {
                _lock.ExitReadLock();
            }

            // Cache it
            _lock.EnterWriteLock();
            try {
                // Check again
                if (_map.TryGetValue(key, out val))
                    return val;

                // Create it
                val = factory();

                // Store it
                _map.Add(key, val);

                // Done
                return val;
            } finally {
                _lock.ExitWriteLock();
            }
        }

19 View Source File : ReadWriteLock.cs
License : Apache License 2.0
Project Creator : tr8dr

public void Lock ()
				{ _lock._lock.EnterReadLock (); }

19 View Source File : ParseOption.cs
License : MIT License
Project Creator : tupac-amaru

public bool Contains(T item)
            {
                rwLock.EnterReadLock();
                try
                {
                    return storage.Contains(item);
                }
                finally
                {
                    rwLock.ExitReadLock();
                }
            }

19 View Source File : ParseOption.cs
License : MIT License
Project Creator : tupac-amaru

public void CopyTo(T[] array, int arrayIndex)
            {
                rwLock.EnterReadLock();
                try
                {
                    storage.CopyTo(array, arrayIndex);
                }
                finally
                {
                    rwLock.ExitReadLock();
                }
            }

19 View Source File : ParseOption.cs
License : MIT License
Project Creator : tupac-amaru

public IEnumerator<T> GetEnumerator()
            {
                rwLock.EnterReadLock();
                try
                {
                    var enumerator = storage.Select(x => x).ToList();
                    return enumerator.GetEnumerator();
                }
                finally
                {
                    rwLock.ExitReadLock();
                }
            }

19 View Source File : Connection.cs
License : MIT License
Project Creator : Unity-Technologies

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 : Unity-Technologies

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();
            }
        }

See More Examples