/// <inheritdoc/> public T this[int index] { get { CheckIndex(index); try { ReaderWriterLock?.EnterReadLock(); return(MemUtil.GetRef <T>(GetPtr(index))); } finally { ReaderWriterLock?.ExitReadLock(); } } set { CheckIndex(index); try { ReaderWriterLock?.EnterWriteLock(); MemUtil.GetRef <T>(GetPtr(index)) = value; } finally { ReaderWriterLock?.ExitWriteLock(); } } }
/// <summary> /// Freezes updates if the collection was created as multithreaded. To resume updates dispose of the returned IDisposable. /// </summary> /// <returns></returns> public IDisposable FreezeUpdates() { _lock?.EnterReadLock(); return(new AnonDisposable(() => { _lock?.ExitReadLock(); })); }
public void Dispose() { if (!disposed) { syncLock?.ExitReadLock(); syncLock = null; disposed = true; } }
public static void EnterExit() { using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim()) { Assert.False(rwls.IsReadLockHeld); rwls.EnterReadLock(); Assert.True(rwls.IsReadLockHeld); rwls.ExitReadLock(); Assert.False(rwls.IsReadLockHeld); Assert.False(rwls.IsUpgradeableReadLockHeld); rwls.EnterUpgradeableReadLock(); Assert.True(rwls.IsUpgradeableReadLockHeld); rwls.ExitUpgradeableReadLock(); Assert.False(rwls.IsUpgradeableReadLockHeld); Assert.False(rwls.IsWriteLockHeld); rwls.EnterWriteLock(); Assert.True(rwls.IsWriteLockHeld); rwls.ExitWriteLock(); Assert.False(rwls.IsWriteLockHeld); Assert.False(rwls.IsUpgradeableReadLockHeld); rwls.EnterUpgradeableReadLock(); Assert.False(rwls.IsWriteLockHeld); Assert.True(rwls.IsUpgradeableReadLockHeld); rwls.EnterWriteLock(); Assert.True(rwls.IsWriteLockHeld); rwls.ExitWriteLock(); Assert.False(rwls.IsWriteLockHeld); Assert.True(rwls.IsUpgradeableReadLockHeld); rwls.ExitUpgradeableReadLock(); Assert.False(rwls.IsUpgradeableReadLockHeld); Assert.True(rwls.TryEnterReadLock(0)); rwls.ExitReadLock(); Assert.True(rwls.TryEnterReadLock(Timeout.InfiniteTimeSpan)); rwls.ExitReadLock(); Assert.True(rwls.TryEnterUpgradeableReadLock(0)); rwls.ExitUpgradeableReadLock(); Assert.True(rwls.TryEnterUpgradeableReadLock(Timeout.InfiniteTimeSpan)); rwls.ExitUpgradeableReadLock(); Assert.True(rwls.TryEnterWriteLock(0)); rwls.ExitWriteLock(); Assert.True(rwls.TryEnterWriteLock(Timeout.InfiniteTimeSpan)); rwls.ExitWriteLock(); } }
public static void ReaderWriterLockSlimPerf() { ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim(); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { rwLock.EnterReadLock(); rwLock.ExitReadLock(); } } }
public void Dispose() { if (_readOnly) { _readerWriterLock?.ExitReadLock(); } else { _readerWriterLock?.ExitWriteLock(); } _readerWriterLock = null; }
protected void ExitReadLock() => _lock?.ExitReadLock();
public static IDisposable UseReadLock(this ReaderWriterLockSlim locker) { locker?.EnterReadLock(); return(new DisposeActionWrapper(() => locker?.ExitReadLock())); }
/// <inheritdoc /> public void Dispose() { _mutex?.ExitReadLock(); }
public static void InvalidExits(LockRecursionPolicy policy) { using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim(policy)) { Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock()); Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock()); Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock()); rwls.EnterReadLock(); Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock()); Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock()); rwls.ExitReadLock(); rwls.EnterUpgradeableReadLock(); Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock()); Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock()); rwls.ExitUpgradeableReadLock(); rwls.EnterWriteLock(); Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock()); Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock()); rwls.ExitWriteLock(); using (Barrier barrier = new Barrier(2)) { Task t = Task.Factory.StartNew(() => { rwls.EnterWriteLock(); barrier.SignalAndWait(); barrier.SignalAndWait(); rwls.ExitWriteLock(); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); barrier.SignalAndWait(); Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock()); barrier.SignalAndWait(); t.GetAwaiter().GetResult(); } } }
public static void WriterToReaderChain() { using (AutoResetEvent are = new AutoResetEvent(false)) using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim()) { rwls.EnterWriteLock(); Task t = Task.Factory.StartNew(() => { Assert.False(rwls.TryEnterReadLock(TimeSpan.FromMilliseconds(10))); Task.Run(() => are.Set()); // ideally this won't fire until we've called EnterReadLock, but it's a benign race in that the test will succeed either way rwls.EnterReadLock(); rwls.ExitReadLock(); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); are.WaitOne(); rwls.ExitWriteLock(); t.GetAwaiter().GetResult(); } }
public IDisposable ReadLock() { rwlSlim.EnterReadLock(); return(new DisposableAction(() => rwlSlim.ExitReadLock())); }
public void Dispose() => Lock?.ExitReadLock();
/// <summary> /// ParseProtocol /// </summary> /// <param name="protocol"></param> /// <returns></returns> public byte[] ParseProtocol(byte[] protocol) { try { ulong callTableId = 0; RemoteTable rt = null; byte[] ret = null; if (protocol[0] == 1) //Protocol 1 { if (protocol[1] != 1) { callTableId = BitConverter.ToUInt64(protocol, 2); _sync.EnterReadLock(); try { if (!_t.TryGetValue(callTableId, out rt)) { //throw new Exception("table can't be find by id"); return(new byte[] { 255 }); //Protocol 255 means error of operation and must raise an exception } } finally { _sync.ExitReadLock(); } } switch (protocol[1]) { case 1: #region "OpenRemoteTable" //Special parsing int tblLen = BitConverter.ToInt32(protocol, 2); string tblName = System.Text.Encoding.UTF8.GetString(protocol.Substring(6, tblLen)); string _fileName = System.IO.Path.Combine(databasePreFolderPath, tblName); _sync.EnterUpgradeableReadLock(); try { if (!_tIds.TryGetValue(_fileName, out callTableId)) { _sync.EnterWriteLock(); try { if (!_tIds.TryGetValue(_fileName, out callTableId)) { tableId++; //Creating directory, if necessary if (directoryIsNotCreated) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(_fileName)); directoryIsNotCreated = false; } rt = new RemoteTable(_fileName, tableId); _t[tableId] = rt; _tIds[_fileName] = tableId; } } finally { _sync.ExitWriteLock(); } } else { _t.TryGetValue(callTableId, out rt); } } finally { _sync.ExitUpgradeableReadLock(); } return(rt.OpenRemoteTable()); #endregion case 2: #region "CloseRemoteTable" return(rt.CloseRemoteTable()); #endregion case 3: #region "DeleteRemoteTable" ret = rt.DeleteRemoteTable(); _sync.EnterWriteLock(); try { _tIds.Remove(rt._fileName); _t.Remove(callTableId); } finally { _sync.ExitWriteLock(); } return(ret); #endregion case 4: #region DataFileWrite return(rt.DataFileWrite(BitConverter.ToInt64(protocol, 10), (protocol[18] == 1), protocol.Substring(19))); #endregion case 5: #region "RollbackFileWrite" return(rt.RollbackFileWrite(BitConverter.ToInt64(protocol, 10), (protocol[18] == 1), protocol.Substring(19))); #endregion case 6: #region "RollbackHelperFileWrite" return(rt.RollbackHelperFileWrite(BitConverter.ToInt64(protocol, 10), (protocol[18] == 1), protocol.Substring(19))); #endregion case 7: #region "DataFileRead" return(rt.DataFileRead(BitConverter.ToInt64(protocol, 10), BitConverter.ToInt32(protocol, 18))); #endregion case 8: #region "RollbackFileRead" return(rt.RollbackFileRead(BitConverter.ToInt64(protocol, 10), BitConverter.ToInt32(protocol, 18))); #endregion case 9: #region "RollbackHelperFileRead" return(rt.RollbackHelperFileRead(BitConverter.ToInt64(protocol, 10), BitConverter.ToInt32(protocol, 18))); #endregion case 10: #region "DataFileFlush" return(rt.DataFileFlush()); #endregion case 11: #region "RollbackFileFlush" return(rt.RollbackFileFlush()); #endregion case 12: #region "RollbackFileRecreate" return(rt.RollbackFileRecreate()); #endregion } } } catch// (Exception ex) { return(new byte[] { 255 }); //throw ex; //Connector must be disconnected and error must be logged } return(null); }
private static void SendHeadersExchange(IConnection connection) { readerWriterLock.EnterReadLock(); try { if (connection.IsOpen) { using (IModel channel = connection.CreateModel()) { channel.ExchangeDeclare("company.exchange.headers", ExchangeType.Headers, true, false, null); channel.QueueDeclare("company.queue.headers", true, false, false, null); Dictionary <string, object> headerOptionsWithAll = new Dictionary <string, object> { { "x-match", "all" }, { "category", "animal" }, { "type", "mammal" } }; channel.QueueBind(queue: "company.queue.headers", exchange: "company.exchange.headers", routingKey: "", arguments: headerOptionsWithAll); Dictionary <string, object> headerOptionsWithAny = new Dictionary <string, object> { { "x-match", "any" }, { "category", "plant" }, { "type", "tree" } }; channel.QueueBind("company.queue.headers", "company.exchange.headers", "", headerOptionsWithAny); PublicationAddress address = new PublicationAddress(exchangeType: ExchangeType.Headers, exchangeName: "company.exchange.headers", routingKey: ""); IBasicProperties properties = channel.CreateBasicProperties(); Dictionary <string, object> messageHeaders = new Dictionary <string, object> { { "category", "animal" }, { "type", "insect" } }; properties.Headers = messageHeaders; channel.BasicPublish(addr: address, basicProperties: properties, body: Encoding.UTF8.GetBytes("Hello from the world of insects")); properties = channel.CreateBasicProperties(); messageHeaders = new Dictionary <string, object> { { "category", "animal" }, { "type", "mammal" }, { "mood", "awesome" } }; properties.Headers = messageHeaders; channel.BasicPublish(addr: address, basicProperties: properties, body: Encoding.UTF8.GetBytes("Hello from the world of awesome mammals")); properties = channel.CreateBasicProperties(); messageHeaders = new Dictionary <string, object> { { "category", "animal" }, { "type", "mammal" } }; properties.Headers = messageHeaders; channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("Hello from the world of mammals")); properties = channel.CreateBasicProperties(); messageHeaders = new Dictionary <string, object> { { "category", "animal" } }; properties.Headers = messageHeaders; channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("Hello from the world of animals")); properties = channel.CreateBasicProperties(); messageHeaders = new Dictionary <string, object> { { "category", "fungi" }, { "type", "champignon" } }; properties.Headers = messageHeaders; channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("Hello from the world of fungi")); properties = channel.CreateBasicProperties(); messageHeaders = new Dictionary <string, object> { { "category", "plant" } }; properties.Headers = messageHeaders; channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("Hello from the world of plants")); properties = channel.CreateBasicProperties(); messageHeaders = new Dictionary <string, object> { { "category", "plant" }, { "type", "tree" } }; properties.Headers = messageHeaders; channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("Hello from the world of trees")); properties = channel.CreateBasicProperties(); messageHeaders = new Dictionary <string, object> { { "mood", "sad" }, { "type", "tree" } }; properties.Headers = messageHeaders; channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("Hello from the world of sad trees")); } } } finally { readerWriterLock.ExitReadLock(); } }
private bool ForkAndExecProcess( string filename, string[] argv, string[] envp, string cwd, bool redirectStdin, bool redirectStdout, bool redirectStderr, bool setCredentials, uint userId, uint groupId, uint[] groups, out int stdinFd, out int stdoutFd, out int stderrFd, bool usesTerminal, bool throwOnNoExec = true) { if (string.IsNullOrEmpty(filename)) { throw new Win32Exception(Interop.Error.ENOENT.Info().RawErrno); } // Lock to avoid races with OnSigChild // By using a ReaderWriterLock we allow multiple processes to start concurrently. s_processStartLock.EnterReadLock(); try { if (usesTerminal) { ConfigureTerminalForChildProcesses(1); } int childPid; // Invoke the shim fork/execve routine. It will create pipes for all requested // redirects, fork a child process, map the pipe ends onto the appropriate stdin/stdout/stderr // descriptors, and execve to execute the requested process. The shim implementation // is used to fork/execve as executing managed code in a forked process is not safe (only // the calling thread will transfer, thread IDs aren't stable across the fork, etc.) int errno = Interop.Sys.ForkAndExecProcess( filename, argv, envp, cwd, redirectStdin, redirectStdout, redirectStderr, setCredentials, userId, groupId, groups, out childPid, out stdinFd, out stdoutFd, out stderrFd); if (errno == 0) { // Ensure we'll reap this process. // note: SetProcessId will set this if we don't set it first. _waitStateHolder = new ProcessWaitState.Holder(childPid, isNewChild: true, usesTerminal); // Store the child's information into this Process object. Debug.Assert(childPid >= 0); SetProcessId(childPid); SetProcessHandle(new SafeProcessHandle(_processId, GetSafeWaitHandle())); return(true); } else { if (!throwOnNoExec && new Interop.ErrorInfo(errno).Error == Interop.Error.ENOEXEC) { return(false); } throw new Win32Exception(errno); } } finally { s_processStartLock.ExitReadLock(); if (_waitStateHolder == null && usesTerminal) { // We failed to launch a child that could use the terminal. s_processStartLock.EnterWriteLock(); ConfigureTerminalForChildProcesses(-1); s_processStartLock.ExitWriteLock(); } } }
private async void btnGenerar_Click(object sender, EventArgs e) { panel1.Controls.Clear(); num = int.Parse(this.textBox1.Text); bmatriz = new Button[num, num]; totalMinas = 0; casillasDescubiertas = 0; cmatriz = await Task.Run(() => { padlock.EnterReadLock(); int n = num; char[,] m = new char[n, n]; padlock.ExitReadLock(); Console.WriteLine(n); Random r = new Random(); for (int i = 0; i < num; i++) { for (int j = 0; j < num; j++) { if (r.Next(10) == 1) { m[i, j] = '*'; totalMinas++; } } } //padlock.EnterWriteLock(); //matriz = m; //padlock.ExitWriteLock(); return(m); } ); cmatriz = await Task.Run(() => { padlock.EnterReadLock(); int n = num; char[,] m = cmatriz; padlock.ExitReadLock(); for (int i = 0; i < num; i++) { for (int j = 0; j < num; j++) { if (!m[i, j].Equals('*')) { int val = 0; if (j + 1 < num) { if (m[i, j + 1].Equals('*')) { val++; } if (i + 1 < num && m[i + 1, j + 1].Equals('*')) { val++; } if (i > 0 && m[i - 1, j + 1].Equals('*')) { val++; } } if (j - 1 >= 0) { if (m[i, j - 1].Equals('*')) { val++; } if (i + 1 < num && m[i + 1, j - 1].Equals('*')) { val++; } if (i > 0 && m[i - 1, j - 1].Equals('*')) { val++; } } if (i + 1 < num && m[i + 1, j].Equals('*')) { val++; } if (i > 0 && m[i - 1, j].Equals('*')) { val++; } m[i, j] = Convert.ToChar(val + 48); } Console.WriteLine(m[i, j]); } } return(m); }); GenerateButtonArrays(num); }
/// <summary> /// Looks up the actual type of an object to be deserialized. /// </summary> /// <param name="nominalType">The nominal type of the object.</param> /// <param name="discriminator">The discriminator.</param> /// <returns>The actual type of the object.</returns> public static Type LookupActualType(Type nominalType, BsonValue discriminator) { if (discriminator == null) { return(nominalType); } // note: EnsureKnownTypesAreRegistered handles its own locking so call from outside any lock EnsureKnownTypesAreRegistered(nominalType); __configLock.EnterReadLock(); try { Type actualType = null; HashSet <Type> hashSet; if (__discriminators.TryGetValue(discriminator, out hashSet)) { foreach (var type in hashSet) { if (nominalType.IsAssignableFrom(type)) { if (actualType == null) { actualType = type; } else { string message = string.Format("Ambiguous discriminator '{0}'.", discriminator); throw new BsonSerializationException(message); } } } } if (actualType == null && discriminator.IsString) { actualType = TypeNameDiscriminator.GetActualType(discriminator.AsString); // see if it's a Type name } if (actualType == null) { string message = string.Format("Unknown discriminator value '{0}'.", discriminator); throw new BsonSerializationException(message); } if (!nominalType.IsAssignableFrom(actualType)) { string message = string.Format( "Actual type {0} is not assignable to expected type {1}.", actualType.FullName, nominalType.FullName); throw new BsonSerializationException(message); } return(actualType); } finally { __configLock.ExitReadLock(); } }
/// <summary> /// Exists the read lock. /// </summary> protected void ExitReadLock() { _lockManager.ExitReadLock(); }
/// <summary> /// Processes a SPARQL Query sending the results to a RDF/SPARQL Results handler as appropriate /// </summary> /// <param name="rdfHandler">RDF Handler</param> /// <param name="resultsHandler">Results Handler</param> /// <param name="query">SPARQL Query</param> public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query) { //Do Handler null checks before evaluating the query if (query == null) { throw new ArgumentNullException("query", "Cannot evaluate a null query"); } if (rdfHandler == null && (query.QueryType == SparqlQueryType.Construct || query.QueryType == SparqlQueryType.Describe || query.QueryType == SparqlQueryType.DescribeAll)) { throw new ArgumentNullException("rdfHandler", "Cannot use a null RDF Handler when the Query is a CONSTRUCT/DESCRIBE"); } if (resultsHandler == null && (query.QueryType == SparqlQueryType.Ask || SparqlSpecsHelper.IsSelectQuery(query.QueryType))) { throw new ArgumentNullException("resultsHandler", "Cannot use a null resultsHandler when the Query is an ASK/SELECT"); } //Handle the Thread Safety of the Query Evaluation #if !NO_RWLOCK ReaderWriterLockSlim currLock = (this._dataset is IThreadSafeDataset) ? ((IThreadSafeDataset)this._dataset).Lock : this._lock; try { currLock.EnterReadLock(); #endif //Reset Query Timers query.QueryExecutionTime = null; query.QueryTime = -1; query.QueryTimeTicks = -1; bool datasetOk = false, defGraphOk = false; try { //Set up the Default and Active Graphs IGraph defGraph; if (query.DefaultGraphs.Any()) { //Default Graph is the Merge of all the Graphs specified by FROM clauses Graph g = new Graph(); foreach (Uri u in query.DefaultGraphs) { if (this._dataset.HasGraph(u)) { g.Merge(this._dataset[u], true); } else { throw new RdfQueryException("A Graph with URI '" + u.ToString() + "' does not exist in this Triple Store, this URI cannot be used in a FROM clause in SPARQL queries to this Triple Store"); } } defGraph = g; this._dataset.SetDefaultGraph(defGraph); } else if (query.NamedGraphs.Any()) { //No FROM Clauses but one/more FROM NAMED means the Default Graph is the empty graph defGraph = new Graph(); this._dataset.SetDefaultGraph(defGraph); } else { defGraph = this._dataset.DefaultGraph; this._dataset.SetDefaultGraph(defGraph); } defGraphOk = true; this._dataset.SetActiveGraph(defGraph); datasetOk = true; //Convert to Algebra and execute the Query SparqlEvaluationContext context = this.GetContext(query); BaseMultiset result; try { context.StartExecution(); ISparqlAlgebra algebra = query.ToAlgebra(); result = context.Evaluate(algebra); //query.Evaluate(context); context.EndExecution(); query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks); query.QueryTime = context.QueryTime; query.QueryTimeTicks = context.QueryTimeTicks; } catch (RdfQueryException) { context.EndExecution(); query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks); query.QueryTime = context.QueryTime; query.QueryTimeTicks = context.QueryTimeTicks; throw; } catch { context.EndExecution(); query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks); query.QueryTime = context.QueryTime; query.QueryTimeTicks = context.QueryTimeTicks; throw; } //Return the Results switch (query.QueryType) { case SparqlQueryType.Ask: case SparqlQueryType.Select: case SparqlQueryType.SelectAll: case SparqlQueryType.SelectAllDistinct: case SparqlQueryType.SelectAllReduced: case SparqlQueryType.SelectDistinct: case SparqlQueryType.SelectReduced: //For SELECT and ASK can populate a Result Set directly from the Evaluation Context //return new SparqlResultSet(context); resultsHandler.Apply(context); break; case SparqlQueryType.Construct: //Create a new Empty Graph for the Results try { rdfHandler.StartRdf(); foreach (String prefix in query.NamespaceMap.Prefixes) { if (!rdfHandler.HandleNamespace(prefix, query.NamespaceMap.GetNamespaceUri(prefix))) { ParserHelper.Stop(); } } //Construct the Triples for each Solution foreach (ISet s in context.OutputMultiset.Sets) { //List<Triple> constructedTriples = new List<Triple>(); try { ConstructContext constructContext = new ConstructContext(rdfHandler, s, false); foreach (IConstructTriplePattern p in query.ConstructTemplate.TriplePatterns.OfType <IConstructTriplePattern>()) { try { if (!rdfHandler.HandleTriple(p.Construct(constructContext))) { ParserHelper.Stop(); } //constructedTriples.Add(((IConstructTriplePattern)p).Construct(constructContext)); } catch (RdfQueryException) { //If we get an error here then we could not construct a specific triple //so we continue anyway } } } catch (RdfQueryException) { //If we get an error here this means we couldn't construct for this solution so the //entire solution is discarded continue; } //h.Assert(constructedTriples); } rdfHandler.EndRdf(true); } catch (RdfParsingTerminatedException) { rdfHandler.EndRdf(true); } catch { rdfHandler.EndRdf(false); throw; } break; case SparqlQueryType.Describe: case SparqlQueryType.DescribeAll: //For DESCRIBE we retrieve the Describe algorithm and apply it ISparqlDescribe describer = query.Describer; describer.Describe(rdfHandler, context); break; default: throw new RdfQueryException("Unknown query types cannot be processed by Leviathan"); } } finally { if (defGraphOk) { this._dataset.ResetDefaultGraph(); } if (datasetOk) { this._dataset.ResetActiveGraph(); } } #if !NO_RWLOCK } finally { currLock.ExitReadLock(); } #endif }
public void Dispose() { _lock?.ExitReadLock(); _lock = null; }
public static void Go() { Int32 x = 0; const Int32 iterations = 10000000; // 10 million // How long does it take to increment x 10 million times // adding the overhead of calling an uncontended SimpleHybridLock? var shl = new SimpleHybridLock(); shl.Enter(); x++; shl.Leave(); Stopwatch sw = Stopwatch.StartNew(); for (Int32 i = 0; i < iterations; i++) { shl.Enter(); x++; shl.Leave(); } Console.WriteLine("Incrementing x in SimpleHybridLock: {0:N0}", sw.ElapsedMilliseconds); // How long does it take to increment x 10 million times // adding the overhead of calling an uncontended ANotherHybridLock? using (var ahl = new AnotherHybridLock()) { ahl.Enter(); x++; ahl.Leave(); sw.Restart(); for (Int32 i = 0; i < iterations; i++) { ahl.Enter(); x++; ahl.Leave(); } Console.WriteLine("Incrementing x in AnotherHybridLock: {0:N0}", sw.ElapsedMilliseconds); } using (var oml = new OneManyLock()) { oml.Enter(true); x++; oml.Leave(); sw.Restart(); for (Int32 i = 0; i < iterations; i++) { oml.Enter(true); x++; oml.Leave(); } Console.WriteLine("Incrementing x in OneManyLock: {0:N0}", sw.ElapsedMilliseconds); } using (var rwls = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion)) { rwls.EnterReadLock(); x++; rwls.ExitReadLock(); sw.Restart(); for (Int32 i = 0; i < iterations; i++) { rwls.EnterReadLock(); x++; rwls.ExitReadLock(); } Console.WriteLine("Incrementing x in ReaderWriterLockSlim: {0:N0}", sw.ElapsedMilliseconds); } var rwl = new ReaderWriterLock(); rwl.AcquireReaderLock(Timeout.Infinite); x++; rwl.ReleaseReaderLock(); sw.Restart(); for (Int32 i = 0; i < iterations; i++) { rwl.AcquireReaderLock(Timeout.Infinite); x++; rwl.ReleaseReaderLock(); } Console.WriteLine("Incrementing x in ReaderWriterLock: {0:N0}", sw.ElapsedMilliseconds); Object l = new Object(); Monitor.Enter(l); x++; Monitor.Exit(l); sw.Restart(); for (Int32 i = 0; i < iterations; i++) { Monitor.Enter(l); x++; Monitor.Exit(l); } Console.WriteLine("Incrementing x in Monitor: {0:N0}", sw.ElapsedMilliseconds); sw.Restart(); for (Int32 i = 0; i < iterations; i++) { lock (l) { x++; } } Console.WriteLine("Incrementing x in lock: {0:N0}", sw.ElapsedMilliseconds); Console.ReadLine(); }
public static void DeadlockAvoidance() { using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim()) { rwls.EnterReadLock(); Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock()); Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock()); Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock()); rwls.ExitReadLock(); rwls.EnterUpgradeableReadLock(); rwls.EnterReadLock(); Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock()); rwls.ExitReadLock(); Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock()); rwls.EnterWriteLock(); Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock()); rwls.ExitWriteLock(); rwls.ExitUpgradeableReadLock(); rwls.EnterWriteLock(); Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock()); Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock()); Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock()); rwls.ExitWriteLock(); } using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion)) { rwls.EnterReadLock(); Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock()); rwls.EnterReadLock(); Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock()); rwls.ExitReadLock(); rwls.ExitReadLock(); rwls.EnterUpgradeableReadLock(); rwls.EnterReadLock(); rwls.EnterUpgradeableReadLock(); rwls.ExitUpgradeableReadLock(); rwls.EnterReadLock(); rwls.ExitReadLock(); rwls.ExitReadLock(); rwls.EnterWriteLock(); rwls.EnterWriteLock(); rwls.ExitWriteLock(); rwls.ExitWriteLock(); rwls.ExitUpgradeableReadLock(); rwls.EnterWriteLock(); rwls.EnterReadLock(); rwls.ExitReadLock(); rwls.EnterUpgradeableReadLock(); rwls.ExitUpgradeableReadLock(); rwls.EnterWriteLock(); rwls.ExitWriteLock(); rwls.ExitWriteLock(); } }
// we can ignore "state" param void ComputeBoundOp(Object state) { IsRunning = true; if (cachedServerTime > 0) { curUtc = cachedServerTime; cachedServerTime = 0; } curUtc++; //申请读锁 #region require Read lock m_readerWriterLock.EnterReadLock(); if (TaskDic != null) { //清空状态 ActionList.Clear(); ToBeRemoved.Clear(); foreach (int TaskId in TaskDic.Keys) { TimerTask task = TaskDic[TaskId]; if (task != null) { task.leftTime = task.endTime - curUtc; task.leftTime = task.leftTime <= 0 ? 0 : task.leftTime; if (task.leftTime == 0 && task.endTime != TimerTask.INFINITY) { ToBeRemoved.Add(TaskId); } if (task.Enabled == false) { ToBeRemoved.Add(TaskId); } if (task.startTime == curUtc) { ActionList.Enqueue(task.handleStart); } if (task.endTime == curUtc) { ActionList.Enqueue(task.handleCompleted); } if (curUtc > task.startTime && (curUtc < task.endTime || task.endTime == TimerTask.INFINITY)) { if (task.frequency == TimerTask.NO_FREUENCY) { // do thing ... } else { if (task.curFre > 1) { task.curFre--; } else { task.curFre = task.frequency; ActionList.Enqueue(task.handleOnEvent); } } } } } } //释放读锁 m_readerWriterLock.ExitReadLock(); #endregion //申请写锁 m_readerWriterLock.EnterWriteLock(); if (TaskDic != null) { foreach (int key in ToBeRemoved) { TaskDic.Remove(key); } } ToBeRemoved.Clear(); //释放写锁 m_readerWriterLock.ExitWriteLock(); // --------- 开始执行 ---------- ThreadPool.QueueUserWorkItem( (actions) => { Action[] WorkList = (actions as Queue <Action>).ToArray(); if (WorkList != null) { foreach (Action work in WorkList) { if (work != null) { try { work(); } catch (Exception ex) { ConsoleEx.DebugLog(ex.Message); } } } } }, ActionList ); //开始下一个时间任务 threadTimer.Change(IntervalPeriod, Timeout.Infinite); }
public static void ReadersMayBeConcurrent() { using (Barrier barrier = new Barrier(2)) using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim()) { Assert.Equal(0, rwls.CurrentReadCount); Task.WaitAll( Task.Run(() => { rwls.EnterReadLock(); barrier.SignalAndWait(); // 1 Assert.True(rwls.IsReadLockHeld); barrier.SignalAndWait(); // 2 Assert.Equal(2, rwls.CurrentReadCount); barrier.SignalAndWait(); // 3 barrier.SignalAndWait(); // 4 rwls.ExitReadLock(); }), Task.Run(() => { barrier.SignalAndWait(); // 1 rwls.EnterReadLock(); barrier.SignalAndWait(); // 2 Assert.True(rwls.IsReadLockHeld); Assert.Equal(0, rwls.WaitingReadCount); barrier.SignalAndWait(); // 3 rwls.ExitReadLock(); barrier.SignalAndWait(); // 4 })); Assert.Equal(0, rwls.CurrentReadCount); } }
void MediaDataReceived(MTClient sender, MediaData mediaData) { //int handle = (int)mediaData.DialogId; Byte[] framedate = new Byte[mediaData.FrameData.Count]; int frametype = 0; Buffer.BlockCopy(mediaData.FrameData.Array, mediaData.FrameData.Offset, framedate, 0, mediaData.FrameData.Count); if (mediaData.FrameType == FrameType.PFrame) { frametype = 4; } else if (mediaData.FrameType == FrameType.IFrame) { frametype = 3; } else if (mediaData.FrameType == FrameType.BFrame) { frametype = 5; } else if (mediaData.FrameType == FrameType.Audio) { frametype = 2; } else if (mediaData.FrameType == FrameType.MJpeg) { frametype = 6; } else { Console.WriteLine("frametype error"); ServiceEnvironment.Instance.Logger.Error("frametype error"); return; } MTSession_lock.EnterReadLock(); MediaStreamSession[] sessions = MediaStreamSessions.ToArray(); MTSession_lock.ExitReadLock(); try { foreach (MediaStreamSession livesession in sessions) { if (livesession.IsConnected()) { bool sendout = livesession.TrySend(frametype, framedate, 100, 10); if (sendout == false) { ThreadPool.QueueUserWorkItem(new WaitCallback(MediaStreamSessionClose), livesession); Console.WriteLine("预览流数据发送超时,主动关闭session"); ServiceEnvironment.Instance.Logger.Info("预览流数据发送超时,主动关闭session"); return; } } else { ThreadPool.QueueUserWorkItem(new WaitCallback(MediaStreamSessionClose), livesession); } } } finally { } }
public void Connect(string host = "localhost", int port = 10111) { Console.WriteLine("Connecting to: {0}:{1}", host, port); try { client.Connect(host, port); client.NoDelay = true; this.NetworkStream = client.GetStream(); Task.Run(() => { while (true) { try { var commandString = ReadCommand(); //Console.WriteLine("Reply from Server: {0}", commandString); var response = Serializer.DeserializeJson <APIResponse>(commandString); CommandReceived(this, new CommandReceivedEventArgs(response, commandString)); } catch (Exception ex) { } } }); Task.Run(() => { while (true) { apiCallQueueLock.EnterReadLock(); var pendingItems = apiCallQueue.Any(); apiCallQueueLock.ExitReadLock(); if (pendingItems) { try { apiCallQueueLock.EnterWriteLock(); var apiCall = apiCallQueue.Dequeue(); apiCallQueueLock.ExitWriteLock(); if (apiCall != null) { WriteObject(apiCall); } } catch (Exception ex) { Console.WriteLine("Error Sending Command: {0}", ex); } } else { Thread.Sleep(60); } } }); } catch (System.Net.Sockets.SocketException e) { Console.WriteLine("Caught exception: {0}", e); } }
public CompiledLanguage Compile(ILanguage language) { Guard.ArgNotNull(language, "language"); if (string.IsNullOrEmpty(language.Id)) { throw new ArgumentException("The language identifier must not be null.", "language"); } CompiledLanguage compiledLanguage; compileLock.EnterReadLock(); try { // for performance reasons we should first try with // only a read lock since the majority of the time // it'll be created already and upgradeable lock blocks if (compiledLanguages.ContainsKey(language.Id)) { return(compiledLanguages[language.Id]); } } finally { compileLock.ExitReadLock(); } compileLock.EnterUpgradeableReadLock(); try { if (compiledLanguages.ContainsKey(language.Id)) { compiledLanguage = compiledLanguages[language.Id]; } else { compileLock.EnterWriteLock(); try { if (string.IsNullOrEmpty(language.Name)) { throw new ArgumentException("The language name must not be null or empty.", "language"); } if (language.Rules == null || language.Rules.Count == 0) { throw new ArgumentException("The language rules collection must not be empty.", "language"); } compiledLanguage = CompileLanguage(language); compiledLanguages.Add(compiledLanguage.Id, compiledLanguage); } finally { compileLock.ExitWriteLock(); } } } finally { compileLock.ExitUpgradeableReadLock(); } return(compiledLanguage); }
public static List <SysExceptionData> Read(DateTime?date = null) { if (date == null) { date = DateTime.Today; } //日志对象集合 List <SysExceptionData> datas = new List <SysExceptionData>(); string filePath = AppContext.BaseDirectory + $"logs\\全局异常\\{date.Value:yyyyMMdd}.log"; //判断日志文件是否存在 if (!File.Exists(filePath)) { filePath = Directory.GetCurrentDirectory() + $"\\logs\\全局异常\\{date.Value:yyyyMMdd}.log"; } //判断文件是否存在 if (!File.Exists(filePath)) { return(datas); } _slimLock.EnterReadLock(); try { //获取日志文件流 var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //读取内容 var reader = new StreamReader(fs); var content = reader.ReadToEnd(); reader.Close(); fs.Close(); /* *处理内容,换行符替换掉,然后在log4net配置文件中在每一写入日志结尾的地方加上 | *这样做的好处是便于在读取日志文件的时候处理日志数据返回给客户端 * 由于是在每一行结束的地方加上| 所有根据Split分割之后最后一个数据必然是空的 *所有Where去除一下。 */ var contentList = content.Replace("\r\n", "").Split('|').Where(w => !string.IsNullOrEmpty(w)); foreach (var item in contentList) { //根据逗号分割单个日志数据的内容 var info = item.Split(','); if (info.Count() < 5 || info.FirstOrDefault()?.Contains("时间") == false) { continue; } //实例化日志对象 SysExceptionData data = new SysExceptionData(); data.CreateTime = Convert.ToDateTime(info[0].Split(':')[1]); data.Level = info[2].Split(':')[1]; data.Summary = info[3].Split(':')[1]; data.UserName = info[4].Split(':')[1]; datas.Add(data); } } finally { //退出 _slimLock.ExitReadLock(); } return(datas.OrderByDescending(bo => bo.CreateTime).ToList()); }
public void Dispose() => _lock.ExitReadLock();
protected override void OnDispose(ReaderWriterLockSlim?target) => target?.ExitReadLock();
public static string DecryptFile(string inputFile, string outputFile, string password, bool base64Decoding = false) { ReaderWriterLockSlim locker = new ReaderWriterLockSlim(); try { locker.EnterReadLock(); byte[] bytesToBeDecrypted = File.ReadAllBytes(inputFile); byte[] passwordBytes = System.Text.Encoding.ASCII.GetBytes(password); passwordBytes = SHA256.Create().ComputeHash(passwordBytes); string writeAt = !string.IsNullOrEmpty(outputFile) ? outputFile : inputFile; if (base64Decoding) { MappingModel mapping = new MappingModel(); if (string.IsNullOrEmpty(outputFile)) { string encryptoSettingsFileName = "encrypto.settings"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var encryptolocalPath = Path.Combine(Path.GetDirectoryName(inputFile), encryptoSettingsFileName); var encryptoPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "encrypto"); if (File.Exists(encryptolocalPath)) { string content = File.ReadAllText(encryptolocalPath); mapping = JsonConvert.DeserializeObject <MappingModel>(content); } else { if (Directory.Exists(encryptoPath)) { var encryptoSettingsPath = Path.Combine(encryptoPath, encryptoSettingsFileName); string content = File.ReadAllText(encryptoSettingsPath); mapping = JsonConvert.DeserializeObject <MappingModel>(content); } } } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var encryptolocalPath = Path.Combine(Path.GetDirectoryName(inputFile), encryptoSettingsFileName); // localFile var encryptoPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".encrypto"); if (File.Exists(encryptolocalPath)) { string contentMapping = File.ReadAllText(encryptolocalPath); mapping = JsonConvert.DeserializeObject <MappingModel>(contentMapping); } else { if (Directory.Exists(encryptoPath)) { var encryptoSettings = Path.Combine(encryptoPath, encryptoSettingsFileName); string contentMapping = File.ReadAllText(encryptoSettings); mapping = JsonConvert.DeserializeObject <MappingModel>(contentMapping); } } } } string base64Content = File.ReadAllText(inputFile, Encoding.UTF8); if (!isValidBase64(base64Content)) { System.Console.WriteLine("Error: Invalid base64"); return("Decryption failed"); } else { byte[] result = System.Convert.FromBase64String(base64Content); byte[] bytesDecrypted = AES.GetDecryptedByteArray(result, passwordBytes); writeAt = string.IsNullOrEmpty(mapping.original) ? writeAt : mapping.original; File.WriteAllBytes(writeAt, bytesDecrypted); } } else { byte[] bytesDecrypted = AES.GetDecryptedByteArray(bytesToBeDecrypted, passwordBytes); File.WriteAllBytes(writeAt, bytesDecrypted); } return("Decryption succeeded"); } catch (Exception) { return("Decryption failed"); } finally { locker.ExitReadLock(); } }
/// <inheritdoc /> public void ReleaseReaderLock() => _locker?.ExitReadLock();
public void Dispose() { _lock?.ExitReadLock(); }
// // This routine is a wrapper around a hashtable containing mappings // of privilege names to LUIDs // private static Luid LuidFromPrivilege(string privilege) { Luid luid; luid.LowPart = 0; luid.HighPart = 0; // // Look up the privilege LUID inside the cache // try { privilegeLock.EnterReadLock(); if (luids.ContainsKey(privilege)) { luid = luids[privilege]; privilegeLock.ExitReadLock(); } else { privilegeLock.ExitReadLock(); if (false == Interop.mincore.LookupPrivilegeValue(null, privilege, out luid)) { int error = Marshal.GetLastWin32Error(); if (error == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY) { throw new OutOfMemoryException(); } else if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } else if (error == Interop.mincore.Errors.ERROR_NO_SUCH_PRIVILEGE) { throw new ArgumentException( SR.Format(SR.Argument_InvalidPrivilegeName, privilege)); } else { Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "LookupPrivilegeValue() failed with unrecognized error code {0}", error)); throw new InvalidOperationException(); } } privilegeLock.EnterWriteLock(); } } finally { if (privilegeLock.IsReadLockHeld) { privilegeLock.ExitReadLock(); } if (privilegeLock.IsWriteLockHeld) { if (!luids.ContainsKey(privilege)) { luids[privilege] = luid; privileges[luid] = privilege; } privilegeLock.ExitWriteLock(); } } return luid; }
public static string EncryptFile(string inputFile, string outputFile, string password, bool base64Encoding = false, bool localOutput = false) { ReaderWriterLockSlim locker = new ReaderWriterLockSlim(); try { locker.EnterReadLock(); byte[] encryptedBytes = File.ReadAllBytes(inputFile); byte[] passwordToByteArray = System.Text.Encoding.ASCII.GetBytes(password); //hash the password with sha256 passwordToByteArray = SHA256.Create().ComputeHash(passwordToByteArray); byte[] encryptedByteArray = AES.GetEncryptedByteArray(encryptedBytes, passwordToByteArray); string writeAt = !string.IsNullOrEmpty(outputFile) ? outputFile : inputFile; if (base64Encoding) { string base64 = System.Convert.ToBase64String(encryptedByteArray, Base64FormattingOptions.None); File.WriteAllText(writeAt, base64, Encoding.UTF8); string encryptoSettingsFileName = "encrypto.settings"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { string encryptoSettingsPath = string.Empty; if (localOutput) { encryptoSettingsPath = Path.Combine(Path.GetDirectoryName(inputFile), encryptoSettingsFileName); } else { var encryptoPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "encrypto"); if (!Directory.Exists(encryptoPath)) { Directory.CreateDirectory(encryptoPath); } encryptoSettingsPath = Path.Combine(encryptoPath, encryptoSettingsFileName); } MappingModel mapping = new MappingModel(); mapping.original = inputFile; mapping.encrypted = outputFile; string content = JsonConvert.SerializeObject(mapping); File.WriteAllText(encryptoSettingsPath, content); // %AppData%/encrypto/encrypto.settings } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { string encryptoSettingsPath = string.Empty; if (localOutput) { encryptoSettingsPath = Path.Combine(Path.GetDirectoryName(inputFile), encryptoSettingsFileName); } else { var encryptoPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".encrypto"); if (!Directory.Exists(encryptoPath)) { Directory.CreateDirectory(encryptoPath); } encryptoSettingsPath = Path.Combine(encryptoPath, encryptoSettingsFileName); } MappingModel mapping = new MappingModel(); mapping.original = inputFile; mapping.encrypted = outputFile; string content = JsonConvert.SerializeObject(mapping); File.WriteAllText(encryptoSettingsPath, content); // ~/.encrypto/encrypto.settings } } else { File.WriteAllBytes(writeAt, encryptedByteArray); } return("encryption succeeded"); } catch (Exception) { return("encryption failed"); } finally { locker.ExitReadLock(); } }