Exemple #1
0
 /// <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();
         }
     }
 }
        private static PortableFileObject AddFileObject
        (
            string filePath,
            PortableDirectorySource directorySource,
            ReaderWriterLockSlim objectsLock,
            Func <PortableDirectorySource, string, PortableFileObject> createObject
        )
        {
            _objectLoadingTask.ThrowIfUnitialised(nameof(_fileObjectDescriber),
                                                  nameof(AddFileObject),
                                                  nameof(RegisterPlatformSpecific));

            string   fileName = Path.GetFileName(filePath);
            DateTime fileTime = _fileObjectDescriber.GetFileCreationTime(filePath);

            PortableFileObject fileObject = createObject(directorySource,
                                                         fileName);

            directorySource.AddObject(fileObject);

            objectsLock?.EnterWriteLock();

            try
            {
                _cachedObjects.Add(fileObject);
            }
            finally
            {
                objectsLock?.ExitWriteLock();
            }

            return(fileObject);
        }
        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();
            }
        }
Exemple #4
0
        public void Dispose()
        {
            if (_readOnly)
            {
                _readerWriterLock?.ExitReadLock();
            }
            else
            {
                _readerWriterLock?.ExitWriteLock();
            }

            _readerWriterLock = null;
        }
Exemple #5
0
        private TRead BodyReadWriteNotify <TRead>(TRead readValue, Func <TRead, TInternalCollection> write, Func <TRead, NotifyCollectionChangedEventArgs> change)
        {
            _lock?.EnterWriteLock();
            _internalCollection = write(readValue);
            var changeValue = change(readValue);

            if (changeValue != null)
            {
                OnCollectionChanged(changeValue);
            }
            _lock?.ExitWriteLock();
            _lock?.ExitUpgradeableReadLock();
            _viewChanged.InvokeAction();
            return(readValue);
        }
        public static int WriteLines <T>([NotNull] this StreamWriter thisValue, [NotNull] ICollection <T> lines, ReaderWriterLockSlim writerLock = null)
        {
            if (lines == null)
            {
                throw new ArgumentNullException(nameof(lines));
            }
            if (lines.Count == 0)
            {
                return(0);
            }

            int result = 0;

            writerLock?.EnterWriteLock();

            try
            {
                if (lines.Count == 1)
                {
                    thisValue.Write(lines.First());
                    result++;
                }
                else
                {
                    foreach (T line in lines.Take(lines.Count - 1))
                    {
                        thisValue.WriteLine(line);
                        result++;
                    }

                    thisValue.Write(lines.Last());
                    result++;
                }
            }
            catch
            {
                result = -1;
            }
            finally
            {
                writerLock?.ExitWriteLock();
            }

            return(result);
        }
Exemple #7
0
 protected virtual void Dispose(bool isDisposing)
 {
     if (isDisposing)
     {
         _lock?.EnterWriteLock();
         try
         {
             _db?.Entries?.Clear();
             _db = null;
         }
         finally
         {
             _lock?.ExitWriteLock();
             _lock?.Dispose();
             _lock = null;
         }
     }
 }
        public static bool WriteLineWithLock <T>([NotNull] this StreamWriter thisValue, T value, ReaderWriterLockSlim writerLock = null)
        {
            if (value == null)
            {
                return(false);
            }
            writerLock?.EnterWriteLock();

            try
            {
                thisValue.WriteLine(value);
                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                writerLock?.ExitWriteLock();
            }
        }
        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();
            }
        }
Exemple #10
0
 /// <inheritdoc />
 public void Dispose()
 {
     _mutex?.ExitWriteLock();
 }
        static void Main(string[] args)
        {
            Program p = new Program();
            //var f = File.Open("D:\\sampletext.txt",FileMode.Open);
            FileStream wstream = new FileStream("D:\\Documents\\reader-writer12.txt", FileMode.Append,
                                                FileAccess.Write, FileShare.ReadWrite);
            //FileStream rstream = new FileStream("D:\\Documents\\reader-writer7.txt", FileMode.Open,
            //                   FileAccess.Read, FileShare.ReadWrite);
            StreamWriter writer = new StreamWriter(wstream);
            //StreamReader r = new StreamReader(rstream);
            string writepath = "D:\\Documents\\reader-writer12.txt";
            string readpath  = "D:\\Documents\\reader-writer12.txt";
            CancellationTokenSource tokensource1 = new CancellationTokenSource();
            CancellationTokenSource tokensource2 = new CancellationTokenSource();
            Thread t  = new Thread(() => { p.Reader(readpath, "Alpha"); });
            Thread t2 = new Thread(() => { p.Reader(readpath, "Phi"); });
            Thread t3 = new Thread(() => { p.Reader(readpath, "Delta"); });
            Thread t4 = new Thread(() => { p.Reader(readpath, "Capa"); });
            Thread t5 = new Thread(() => { p.write(writer, 5000000, tokensource1.Token); });
            Thread t6 = new Thread(() => { p.write(writer, 3000000, tokensource2.Token); });

            t.Name  = "reader1";
            t2.Name = "reader2";
            t3.Name = "reader3";
            t4.Name = "reader4";
            t5.Name = "writer1";
            t6.Name = "writer2";

            t.Start();
            t2.Start();
            t3.Start();
            t4.Start();
            t5.Start();
            t6.Start();
            Thread.Sleep(300000);
            rwlock.EnterWriteLock();
            if (tokensource1.Token.CanBeCanceled)
            {
                tokensource1.Cancel();
            }
            if (tokensource2.Token.CanBeCanceled)
            {
                tokensource2.Cancel();
            }
            rwlock.ExitWriteLock();
            t.Join();
            t2.Join();

            lock (Lock)
            {
                flag = 1;
                writehandle.Set();
                p.linelist.Add("TERMINATE");
                writehandle.Set();
                p.linelist.Add("TERMINATE");
            }
            t3.Join();
            t4.Join();
            t5.Join();
            t6.Join();

            //writer.Close();
            //r.Close();

            //Console.Write(Program.line);
            Console.WriteLine("Total number of Key:Value pairs written to file= " + linecount);
            Console.ReadKey();
        }
 public void Dispose()
 {
     _readerWriterLock?.ExitWriteLock();
     _readerWriterLock = null;
 }
Exemple #13
0
 public static IDisposable UseWriteLock(this ReaderWriterLockSlim locker)
 {
     locker?.EnterWriteLock();
     return(new DisposeActionWrapper(() => locker?.ExitWriteLock()));
 }
Exemple #14
0
        private void SetEntry(CacheEntry entry)
        {
            var utcNow = _clock.UtcNow;

            DateTimeOffset? absoluteExpiration = null;
            if (entry._absoluteExpirationRelativeToNow.HasValue)
            {
                absoluteExpiration = utcNow + entry._absoluteExpirationRelativeToNow;
            }
            else if (entry._absoluteExpiration.HasValue)
            {
                absoluteExpiration = entry._absoluteExpiration;
            }

            // Applying the option's absolute expiration only if it's not already smaller.
            // This can be the case if a dependent cache entry has a smaller value, and
            // it was set by cascading it to its parent.
            if (absoluteExpiration.HasValue)
            {
                if (!entry._absoluteExpiration.HasValue || absoluteExpiration.Value < entry._absoluteExpiration.Value)
                {
                    entry._absoluteExpiration = absoluteExpiration;
                }
            }

            // Initialize the last access timestamp at the time the entry is added
            entry.LastAccessed = utcNow;

            var added = false;
            CacheEntry priorEntry;

            _entryLock.EnterWriteLock();
            try
            {

                if (_entries.TryGetValue(entry.Key, out priorEntry))
                {
                    _entries.Remove(entry.Key);
                    priorEntry.SetExpired(EvictionReason.Replaced);
                }

                if (!entry.CheckExpired(utcNow))
                {
                    _entries[entry.Key] = entry;
                    entry.AttachTokens();
                    added = true;
                }
            }
            finally
            {
                _entryLock.ExitWriteLock();
            }

            if (priorEntry != null)
            {
                priorEntry.InvokeEvictionCallbacks();
            }

            if (!added)
            {
                entry.InvokeEvictionCallbacks();
            }

            StartScanForExpiredItems();
        }
 public static void WriterToUpgradeableReaderChain()
 {
     using (AutoResetEvent are = new AutoResetEvent(false))
     using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
     {
         rwls.EnterWriteLock();
         Task t = Task.Factory.StartNew(() =>
         {
             Assert.False(rwls.TryEnterUpgradeableReadLock(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.EnterUpgradeableReadLock();
             rwls.ExitUpgradeableReadLock();
         }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
         are.WaitOne();
         rwls.ExitWriteLock();
         t.GetAwaiter().GetResult();
     }
 }
Exemple #16
0
        public void SuspendRequested(object sender, RubberduckStatusSuspendParserEventArgs e)
        {
            if (ParsingSuspendLock.IsReadLockHeld)
            {
                e.Result = SuspensionOutcome.ReadLockAlreadyHeld;
                const string errorMessage =
                    "A suspension action was attempted while a read lock was held. This indicates a bug in the code logic as suspension should not be requested from same thread that has a read lock.";
                Logger.Error(errorMessage);

                Debug.Assert(false, errorMessage);

                return;
            }

            object parseRequestor = null;

            try
            {
                if (!ParsingSuspendLock.TryEnterWriteLock(e.MillisecondsTimeout))
                {
                    e.Result = SuspensionOutcome.TimedOut;
                    return;
                }

                lock (SuspendStackSyncObject)
                {
                    _isSuspended = true;
                }

                var originalStatus = State.Status;
                if (!e.AllowedRunStates.Contains(originalStatus))
                {
                    e.Result = SuspensionOutcome.IncompatibleState;
                    return;
                }
                _parserStateManager.SetStatusAndFireStateChanged(e.Requestor, ParserState.Busy,
                                                                 CancellationToken.None);
                e.BusyAction.Invoke();
            }
            catch (OperationCanceledException ex)
            {
                e.Result = SuspensionOutcome.Canceled;
                e.EncounteredException = ex;
            }
            catch (Exception ex)
            {
                e.Result = SuspensionOutcome.UnexpectedError;
                e.EncounteredException = ex;
            }
            finally
            {
                lock (SuspendStackSyncObject)
                {
                    _isSuspended = false;
                    if (_requestorStack.TryPop(out var lastRequestor))
                    {
                        _requestorStack.Clear();
                        parseRequestor = lastRequestor;
                    }

                    // Though there were no reparse requests, we need to reset the state before we release the
                    // write lock to avoid introducing discrepancy in the parser state due to readers being
                    // blocked. Any reparse requests must be done outside the write lock; see further below.
                    if (parseRequestor == null)
                    {
                        // We cannot make any assumptions about the original state, nor do we know
                        // anything about resuming the previous state, so we must delegate the state
                        // evaluation to the state manager.
                        _parserStateManager.EvaluateOverallParserState(CancellationToken.None);
                    }
                }

                if (ParsingSuspendLock.IsWriteLockHeld)
                {
                    ParsingSuspendLock.ExitWriteLock();
                }

                if (e.Result == SuspensionOutcome.Pending)
                {
                    e.Result = SuspensionOutcome.Completed;
                }
            }

            // Any reparse requests must be done outside the write lock to avoid deadlocks
            if (parseRequestor != null)
            {
                BeginParse(parseRequestor);
            }
        }
 void IDisposable.Dispose()
 {
     _rwLock.ExitWriteLock();
 }
        /// <summary>
        /// Provide the list of attributes applied to the specified member.
        /// </summary>
        /// <param name="reflectedType">The reflectedType the type used to retrieve the memberInfo.</param>
        /// <param name="member">The member to supply attributes for.</param>
        /// <returns>The list of applied attributes.</returns>
        public override IEnumerable <Attribute> GetCustomAttributes(Type reflectedType, System.Reflection.MemberInfo member)
        {
            if (member == null)
            {
                throw new ArgumentNullException(nameof(member));
            }

            // Now edit the attributes returned from the base type
            List <Attribute> cachedAttributes = null;
            var typeInfo = member as TypeInfo;

            if (typeInfo != null)
            {
                var memberInfo = typeInfo as MemberInfo;
                _lock.EnterReadLock();
                try
                {
                    _memberInfos.TryGetValue(memberInfo, out cachedAttributes);
                }
                finally
                {
                    _lock.ExitReadLock();
                }
                if (cachedAttributes == null)
                {
                    _lock.EnterWriteLock();
                    try
                    {
                        //Double check locking another thread may have inserted one while we were away.
                        if (!_memberInfos.TryGetValue(memberInfo, out cachedAttributes))
                        {
                            List <Attribute> attributeList;
                            foreach (Tuple <object, List <Attribute> > element in EvaluateThisTypeInfoAgainstTheConvention(typeInfo))
                            {
                                attributeList = element.Item2;
                                if (attributeList != null)
                                {
                                    var mi = element.Item1 as MemberInfo;
                                    if (mi != null)
                                    {
                                        if (mi != null && (mi is ConstructorInfo || mi is TypeInfo || mi is PropertyInfo || mi is MethodInfo))
                                        {
                                            if (!_memberInfos.TryGetValue(mi, out List <Attribute> memberAttributes))
                                            {
                                                _memberInfos.Add(mi, element.Item2);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        var pi = element.Item1 as ParameterInfo;
                                        if (pi == null)
                                        {
                                            throw new Exception(SR.Diagnostic_InternalExceptionMessage);
                                        }

                                        // Item contains as Constructor parameter to configure
                                        if (!_parameters.TryGetValue(pi, out List <Attribute> parameterAttributes))
                                        {
                                            _parameters.Add(pi, element.Item2);
                                        }
                                    }
                                }
                            }
                        }

                        // We will have updated all of the MemberInfos by now so lets reload cachedAttributes with the current store
                        _memberInfos.TryGetValue(memberInfo, out cachedAttributes);
                    }
                    finally
                    {
                        _lock.ExitWriteLock();
                    }
                }
            }
            else if (member is PropertyInfo || member is ConstructorInfo || member is MethodInfo)
            {
                cachedAttributes = ReadMemberCustomAttributes(reflectedType, member);
            }

            IEnumerable <Attribute> appliedAttributes;

            if (!(member is TypeInfo) && member.DeclaringType != reflectedType)
            {
                appliedAttributes = Enumerable.Empty <Attribute>();
            }
            else
            {
                appliedAttributes = member.GetCustomAttributes <Attribute>(false);
            }

            return(cachedAttributes == null ? appliedAttributes : appliedAttributes.Concat(cachedAttributes));
        }
    public int RunTest()
    {
        bool lockTaken = false;
        int  retCode   = 25;

        try
        {
            lockTaken = false;
            Console.WriteLine("Attempting rwls.TryEnterUpgradeableReadLock(-2647); on unowned lock");
            lockTaken = rwls.TryEnterUpgradeableReadLock(-2647);
            retCode   = -100;
            Console.WriteLine("Expected exception but aquired lock. Failing test.");
        }
        catch (ArgumentException ae)
        {
            retCode = retCode + 25;
            Console.WriteLine("As expected: Caught ArgumentException\n{0}", ae.Message);
        }
        finally
        {
            if (lockTaken)
            {
                rwls.ExitUpgradeableReadLock();
            }
        }

        try
        {
            lockTaken = false;
            Console.WriteLine();
            Console.WriteLine("Attempting rwls.TryEnterReadLock(-2647); on unowned lock");
            lockTaken = rwls.TryEnterReadLock(-2647);
            retCode   = -110;
            Console.WriteLine("Expected exception but aquired lock. Failing test.");
        }
        catch (ArgumentException ae)
        {
            retCode = retCode + 25;
            Console.WriteLine("As expected: Caught ArgumentException\n{0}", ae.Message);
        }
        finally
        {
            if (lockTaken)
            {
                rwls.ExitReadLock();
            }
        }

        try
        {
            lockTaken = false;
            Console.WriteLine();
            Console.WriteLine("Attempting rwls.TryEnterWriteLock(-2647); on unowned lock");
            lockTaken = rwls.TryEnterWriteLock(-2647);
            retCode   = -120;
            Console.WriteLine("Expected exception but aquired lock. Failing test.");
        }
        catch (ArgumentException ae)
        {
            retCode = retCode + 25;
            Console.WriteLine("As expected: Caught ArgumentException\n{0}", ae.Message);
        }
        finally
        {
            if (lockTaken)
            {
                rwls.ExitWriteLock();
            }
        }

        return(retCode);
    }
Exemple #20
0
        public void Subscribe(object subscriber)
        {
            AssertArg.IsNotNull(subscriber, nameof(subscriber));

            var weakReference = new WeakReference(subscriber);

            Type subscriberType = subscriber.GetType();

            List <Type> subscriptionInterfaces;

            if (!typeInterfaceCache.TryGetValue(subscriberType, out subscriptionInterfaces))
            {
                var implementedInterfaces = subscriberType.GetTypeInfo().ImplementedInterfaces;

                foreach (Type implementedInterface in implementedInterfaces)
                {
                    if (implementedInterface.IsGenericType() &&
                        implementedInterface.GetGenericTypeDefinition()
                        == typeof(IMessageSubscriber <>))
                    {
                        if (subscriptionInterfaces == null)
                        {
                            subscriptionInterfaces = new List <Type>();
                        }

                        subscriptionInterfaces.Add(implementedInterface);
                    }
                }

                typeInterfaceCache[subscriberType] = subscriptionInterfaces;
            }

            if (subscriptionInterfaces == null)
            {
                /* No IMessageSubscriber interfaces implemented by the subsciber type. */
                return;
            }

            lockSlim.EnterWriteLock();
            try
            {
                foreach (Type interfaceType in subscriptionInterfaces)
                {
                    bool        possibleDuplicate = false;
                    List <Type> typesForThisMessage;
                    if (registeredTypes.TryGetValue(interfaceType, out typesForThisMessage))
                    {
                        if (typesForThisMessage.Contains(subscriberType))
                        {
                            possibleDuplicate = true;
                        }
                    }
                    else
                    {
                        typesForThisMessage            = new List <Type>();
                        registeredTypes[interfaceType] = typesForThisMessage;
                    }

                    typesForThisMessage.Add(subscriberType);

                    List <WeakReference> subscribers = GetSubscribersNonLocking(interfaceType);

                    if (possibleDuplicate)
                    {
                        /* We may want to improve search complexity here for large sets;
                         * perhaps using a ConditionalWeakTable. */
                        foreach (WeakReference reference in subscribers)
                        {
                            if (reference.Target == subscriber)
                            {
                                return;
                            }
                        }
                    }

                    subscribers.Add(weakReference);
                }
            }
            finally
            {
                lockSlim.ExitWriteLock();
            }
        }
Exemple #21
0
        public static ImageSource GetIcon(string path, double size)
        {
            string key = path + "@" + size.ToString();

            ImageSource image = null;

            IconCacheLock.EnterReadLock();
            bool bFound = IconCache.TryGetValue(key, out image);

            IconCacheLock.ExitReadLock();
            if (bFound)
            {
                return(image);
            }

            try
            {
                var pathIndex = TextHelpers.Split2(path, "|");

                if (IsImageFileName(pathIndex.Item1))
                {
                    try
                    {
                        image = new BitmapImage(new Uri(pathIndex.Item1));
                    }
                    catch { }
                }
                else
                {
                    IconExtractor extractor = new IconExtractor(pathIndex.Item1);
                    int           index     = MiscFunc.parseInt(pathIndex.Item2);
                    if (index < extractor.Count)
                    {
                        image = ToImageSource(extractor.GetIcon(index, new System.Drawing.Size((int)size, (int)size)));
                    }
                }

                if (image == null)
                {
                    if (File.Exists(NtUtilities.NtOsKrnlPath)) // if running in WOW64 this does not exist
                    {
                        image = ToImageSource(Icon.ExtractAssociatedIcon(NtUtilities.NtOsKrnlPath));
                    }
                    else // fall back to an other icon
                    {
                        image = ToImageSource(Icon.ExtractAssociatedIcon(NtUtilities.Shell32Path));
                    }
                }

                image.Freeze();
            }
            catch { }

            IconCacheLock.EnterWriteLock();
            if (!IconCache.ContainsKey(key))
            {
                IconCache.Add(key, image);
            }
            IconCacheLock.ExitWriteLock();
            return(image);
        }
Exemple #22
0
 public void SaveUserStateValue(string state)
 {
     SessionLock.EnterWriteLock();
     httpContext.Session[CacheId + "_state"] = state;
     SessionLock.ExitWriteLock();
 }
        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 WritersAreMutuallyExclusiveFromWriters()
 {
     using (Barrier barrier = new Barrier(2))
     using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
     {
         Task.WaitAll(
             Task.Run(() =>
             {
                 rwls.EnterWriteLock();
                 barrier.SignalAndWait();
                 Assert.True(rwls.IsWriteLockHeld);
                 barrier.SignalAndWait();
                 rwls.ExitWriteLock();
             }),
             Task.Run(() =>
             {
                 barrier.SignalAndWait();
                 Assert.False(rwls.TryEnterWriteLock(0));
                 Assert.False(rwls.IsReadLockHeld);
                 barrier.SignalAndWait();
             }));
     }
 }
 public IDisposable AcquireWriteLock()
 {
     AssertDisposed();
     _rwlock.EnterWriteLock();
     return(Disposable.Create(() => _rwlock.ExitWriteLock()));
 }
Exemple #26
0
        /// <summary>
        /// Tries to enter the lock in write mode.
        /// </summary>
        /// <returns>A disposable to exit the lock from write mode.</returns>
        public IDisposable Write()
        {
            _lock.EnterWriteLock();

            return(new AnonymousDisposable(_ => _lock.ExitWriteLock()));
        }
Exemple #27
0
 public void ExitWriteLock()
 {
     _lock.ExitWriteLock();
 }
 /// <inheritdoc />
 public void ReleaseWriterLock() => _locker?.ExitWriteLock();
Exemple #29
0
 public void Reset()
 {
     _lock.EnterWriteLock();
     _value = 0;
     _lock.ExitWriteLock();
 }
Exemple #30
0
 protected void ExitWriteLock() => _lock?.ExitWriteLock();
Exemple #31
0
 public void Dispose()
 {
     _lock?.ExitWriteLock();
     _lock = null;
 }
Exemple #32
0
        private static void WriteLogTimer(object state)
        {
            var LogPath = AppDomain.CurrentDomain.BaseDirectory + @"\App_Data\Log\" + DateTime.Now.ToString("yyyyMMdd") + @"\";

            if (ENVConfig.IsLinux)
            {
                LogPath = LogPath.Replace("\\", "/");                   //Linux环境处理
            }
            if (!Directory.Exists(LogPath))
            {
                Directory.CreateDirectory(LogPath);
            }

            var dt = (DateTime)state;

            try
            {
                lock (TimerListLock)
                {
                    var rlist = TimerList.Where(p => p.addTime <= dt).ToList();
                    foreach (var item in rlist)
                    {
                        TimerList.Remove(item);
                    }
                }
            }
            catch //(Exception ex)
            {
            }

            try
            {
                LogWriteLock.EnterWriteLock();
                string[] keys = new string[0];
                lock (QueueLock)
                {
                    keys = logs.Keys.ToArray();
                }
                foreach (var logfile in keys)
                {
                    var qu = GetValue(logs, logfile);
                    if (qu.Count < 1)
                    {
                        continue;
                    }
                    string log = "";
                    lock (QueueLock)
                    {
                        log = string.Join("\r\n", qu.ToList());
                        qu.Clear();
                        File.AppendAllText(LogPath + DateTime.Now.ToString("yyyyMMdd_HH") + logfile, log + "\r\n");
                    }
                }
            }
            catch (Exception ex)
            {
                Exception(ex);
            }
            finally
            {
                //退出写入模式,释放资源占用
                LogWriteLock.ExitWriteLock();
            }
        }
Exemple #33
0
        public int Put(Stream src, IActivityIOPath dst, Dev2CRUDOperationTO args, string whereToPut, List <string> filesToCleanup)
        {
            int result = -1;

            using (src)
            {
                //2013.05.29: Ashley Lewis for bug 9507 - default destination to source directory when destination is left blank or if it is not a rooted path
                if (!Path.IsPathRooted(dst.Path))
                {
                    //get just the directory path to put into
                    if (whereToPut != null)
                    {
                        //Make the destination directory equal to that directory
                        dst = ActivityIOFactory.CreatePathFromString(whereToPut + "\\" + dst.Path, dst.Username, dst.Password);
                    }
                }
                if ((args.Overwrite) || (!args.Overwrite && !FileExist(dst)))
                {
                    _fileLock.EnterWriteLock();
                    try{
                        if (!RequiresAuth(dst))
                        {
                            using (src)
                            {
                                File.WriteAllBytes(dst.Path, src.ToByteArray());
                                result = (int)src.Length;
                            }
                        }
                        else
                        {
                            // handle UNC path
                            SafeTokenHandle safeTokenHandle;
                            bool            loginOk = LogonUser(ExtractUserName(dst), ExtractDomain(dst), dst.Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);


                            if (loginOk)
                            {
                                using (safeTokenHandle)
                                {
                                    WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                                    using (WindowsImpersonationContext impersonatedUser = newID.Impersonate())
                                    {
                                        // Do the operation here
                                        using (src)
                                        {
                                            File.WriteAllBytes(dst.Path, src.ToByteArray());
                                            result = (int)src.Length;
                                        }

                                        // remove impersonation now
                                        impersonatedUser.Undo();
                                    }
                                }
                            }
                            else
                            {
                                // login failed
                                throw new Exception("Failed to authenticate with user [ " + dst.Username + " ] for resource [ " + dst.Path + " ] ");
                            }
                        }
                    }
                    finally
                    {
                        _fileLock.ExitWriteLock();
                    }
                }
            }
            return(result);
        }
Exemple #34
0
        private static string GetCallerSignature(MethodBase caller)
        {
            string signature;

            _methodSignaturesLock.EnterReadLock();
            bool signatureFound = _methodSignatures.TryGetValue(caller, out signature);

            _methodSignaturesLock.ExitReadLock();

            if (!signatureFound)
            {
                System.Text.StringBuilder signatureBuilder = new StringBuilder();

                if (caller.IsPrivate)
                {
                    signatureBuilder.Append("private ");
                }
                if (caller.IsPublic)
                {
                    signatureBuilder.Append("public ");
                }
                if (caller.IsStatic)
                {
                    signatureBuilder.Append("static ");
                }
                if (caller.IsAbstract)
                {
                    signatureBuilder.Append("abstract ");
                }
                if (caller.IsVirtual)
                {
                    signatureBuilder.Append("virtual ");
                }

                MethodInfo      mi = caller as MethodInfo;
                ConstructorInfo ci = caller as ConstructorInfo;

                if (mi != null)
                {
                    signatureBuilder.Append(mi.ReturnType.Name);
                }
                if (ci != null)
                {
                    signatureBuilder.Append(ci.DeclaringType.Name);
                }

                signatureBuilder.Append(" ");
                signatureBuilder.Append(caller.Name);

                if (mi != null)
                {
                    Type[] genericArgumentTypes = mi.GetGenericArguments();

                    if (genericArgumentTypes != null && genericArgumentTypes.Length > 0)
                    {
                        signatureBuilder.Append("<");
                        bool firstGenericArgument = true;
                        foreach (Type genericArgumentType in genericArgumentTypes)
                        {
                            if (!firstGenericArgument)
                            {
                                signatureBuilder.Append(", ");
                            }
                            else
                            {
                                firstGenericArgument = false;
                            }

                            signatureBuilder.Append(genericArgumentType.Name);
                        }
                        signatureBuilder.Append(">");
                    }
                }

                signatureBuilder.Append("(");

                bool firstParameter = true;
                foreach (ParameterInfo paremeter in caller.GetParameters())
                {
                    if (!firstParameter)
                    {
                        signatureBuilder.Append(", ");
                    }
                    else
                    {
                        firstParameter = false;
                    }

                    signatureBuilder.Append(paremeter.ParameterType.Name);
                    signatureBuilder.Append(" ");
                    signatureBuilder.Append(paremeter.Name);
                }

                signatureBuilder.Append(")");

                signature = signatureBuilder.ToString();

                _methodSignaturesLock.EnterWriteLock();
                _methodSignatures.Add(caller, signature);
                _methodSignaturesLock.ExitWriteLock();
            }

            return(signature);
        }
Exemple #35
0
 protected override void ExitLock(ReaderWriterLockSlim readerWriterLockSlim)
 {
     readerWriterLockSlim.ExitWriteLock();
 }