Exemplo n.º 1
0
        public ActionResult CreateGame(MultiPlayerGameData multiPlayerGame)
        {
            bool gotLock     = false;
            Guid guid        = Guid.NewGuid();
            Game CurrentGame = null;

            if (ValidatingNewGameForPlayer(null))
            {
                try
                {
                    LockListGameDoesntStart.AcquireWriterLock(timeOut);
                    ListGameDoesntStart.Add(guid, new WeakReference <Game>(CurrentGame = new Game(multiPlayerGame)
                    {
                        IdentifyGuid = guid
                    }));
                }
                catch
                {
                }
                finally
                {
                    gotLock = LockListGameDoesntStart.IsWriterLockHeld;
                    LockListGameDoesntStart.ReleaseWriterLock();
                }
            }
            else
            {
                return(Json(new { GUID = (string)null }));
            }
            if (gotLock)
            {
                CurrentGame.Register(UserFiche.CurentUser);
                Game.GetUserBySesionFicheUser().UserCanStart = true;
                return(Json(new { GUID = guid.ToString() }));
            }
            throw new NotSupportedException("Nie udało się stworzyć nowej gry");
        }
    static void Main()
    {
        ReaderWriterLock rwLock = new ReaderWriterLock();

        rwLock.AcquireWriterLock(Timeout.Infinite);
        rwLock.AcquireReaderLock(Timeout.Infinite);

        if (rwLock.IsReaderLockHeld)
        {
            Console.WriteLine("Reader lock held.");
            rwLock.ReleaseReaderLock();
        }
        else if (rwLock.IsWriterLockHeld)
        {
            Console.WriteLine("Writer lock held.");
            rwLock.ReleaseWriterLock();
        }
        else
        {
            Console.WriteLine("No locks held.");
        }

        if (rwLock.IsReaderLockHeld)
        {
            Console.WriteLine("Reader lock held.");
            rwLock.ReleaseReaderLock();
        }
        else if (rwLock.IsWriterLockHeld)
        {
            Console.WriteLine("Writer lock held.");
            rwLock.ReleaseWriterLock();
        }
        else
        {
            Console.WriteLine("No locks held.");
        }
    }
Exemplo n.º 3
0
        static void LoadSettings()
        {
            settingsLock.AcquireWriterLock(Timeout.Infinite);

            try
            {
                if (cache != null)
                {
                    cache.Dispose();
                }

                _settings = ConfigurationProvider.Settings;

                //  bool validLicense = Alachisoft.NCache.ContentOptimization.Licensing.LicesnseManager.IsLicenseValid;

                /*  if (!validLicense)
                 * {
                 *    FileBasedTraceProvider.Current.WriteTrace(TraceSeverity.CriticalEvent, "License not verified");
                 *    _settings.EnableViewstateCaching = false;
                 * }
                 */

                if (_settings.Enabled)
                {
                    if (_settings.CacheSettings == null)
                    {
                        throw new Exception("Cache settings not set");
                    }

                    var cacheAdapter = new CacheAdapter(_settings.CacheSettings.CacheName);

                    cacheAdapter.RetryInterval = _settings.CacheSettings.ConnectionRetryInterval.HasValue ? _settings.CacheSettings.ConnectionRetryInterval.Value : 300;
                    cacheAdapter.Load();

                    if (_settings.CacheSettings.Expiration == null)
                    {
                        throw new Exception("Expiration settings not set");
                    }

                    cacheAdapter.DefaultExpiration = _settings.CacheSettings.Expiration.Convert();

                    cache = cacheAdapter.GetSynchronized(settingsLock);
                }
            }
            finally
            {
                settingsLock.ReleaseWriterLock();
            }
        }
Exemplo n.º 4
0
        protected override void PurgeCache(object sender, System.Timers.ElapsedEventArgs e)
        {
            ReaderWriterLock readWriteLock = new ReaderWriterLock();

            System.Threading.Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; // This process is not critical as according to add or update.

            if (!Monitor.TryEnter(isPurging))
            {
                return;
            }

            try
            {
                readWriteLock.AcquireWriterLock(MAX_LOCK_WAIT);

                try
                {
                    List <object> expiredCacheObjects = new List <object>();

                    foreach (TimedCacheKey loopExpiredCacheObject in timedStorage.Keys)
                    {
                        if (loopExpiredCacheObject.ExpirationDate < e.SignalTime)
                        {
                            expiredCacheObjects.Add(loopExpiredCacheObject);
                        }
                        else
                        {
                            break;
                        }
                    }

                    foreach (object key in expiredCacheObjects)
                    {
                        TimedCacheKey timedCacheKey = timedStorageIndex[key];
                        timedStorageIndex.Remove(timedCacheKey.Key);

                        timedStorage.Remove(timedCacheKey);
                    }
                }
                finally
                {
                    readWriteLock.ReleaseWriterLock();
                }
            }
            finally
            {
                Monitor.Exit(isPurging);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// 从库中读取对应条件的数据
        /// </summary>
        private void dbGetPrdctTest(string cmdText)
        {
            if (string.IsNullOrEmpty(cmdText))
            {
                return;
            }
            try
            {
                rwLockLpt.AcquireWriterLock(CHECKINTERVAL);//申请写锁(超过设定时间退出等待)
                try
                {
                    this.listPrdctTest.Clear();//清空上次数据

                    DataTable dtPrdctTest = DatabaseUtils.GetDataTable(cmdText);
                    if (dtPrdctTest != null && dtPrdctTest.Rows.Count > 0)
                    {
                        int serNumber = 1;
                        foreach (DataRow item in dtPrdctTest.Rows)
                        {
                            PrdctTestBindEntity prdctTest = new PrdctTestBindEntity();
                            prdctTest.SerNumber    = serNumber++;
                            prdctTest.Id           = Convert.ToInt64(item["Id"]);
                            prdctTest.PrdctId      = Convert.ToInt64(item["ProductId"]);
                            prdctTest.PrdctNumber  = Convert.ToString(item["PrdctNumber"]);
                            prdctTest.TreatType    = Convert.ToString(item["TreatType"]);  //处理类型
                            prdctTest.WeDuration   = Convert.ToString(item["WeDuration"]); //白锈时长
                            prdctTest.ReDuration   = Convert.ToString(item["ReDuration"]);
                            prdctTest.StartTime    = Convert.ToString(item["StartTime"]);
                            prdctTest.WeLossTime   = Convert.ToString(item["WeLossTime"]);
                            prdctTest.ReLossTime   = Convert.ToString(item["ReLossTime"]);
                            prdctTest.WeEndTime    = Convert.ToString(item["WeEndTime"]);
                            prdctTest.ReEndTime    = Convert.ToString(item["ReEndTime"]);
                            prdctTest.WeTestResult = Convert.ToString(item["WeTestResult"]);
                            prdctTest.ReTestResult = Convert.ToString(item["ReTestResult"]);
                            prdctTest.Remark       = Convert.ToString(item["PrdctTestRemark"]);
                            this.listPrdctTest.Add(prdctTest);
                        }
                    }
                }
                finally
                {
                    rwLockLpt.ReleaseWriterLock();//释放写锁
                }
            }
            catch (Exception ex)
            {
                Logger.Error(MethodBase.GetCurrentMethod(), "加载产品数据异常:" + ex.Message);
            }
        }
        /** <inheritdoc /> */
        override public void Close(bool waitCompletion)
        {
            busyLock.AcquireWriterLock(Timeout.Infinite);

            try {
                if (closed)
                {
                    return;
                }

                closed = true;
            }
            finally {
                busyLock.ReleaseWriterLock();
            }

            IList <GridClientFuture> reqs;

            lock (pendingReqs) {
                reqs = new List <GridClientFuture>(pendingReqs);

                pendingReqs.Clear();
            }

            if (waitCompletion)
            {
                foreach (GridClientFuture req in reqs)
                {
                    try {
                        req.WaitDone();
                    }
                    catch (GridClientException e) {
                        Dbg.WriteLine("Failed to get waiting result: {0}", e);
                    }
                }
            }
            else
            {
                foreach (GridClientFuture req in reqs)
                {
                    req.Fail(() => {
                        throw new GridClientClosedException("Failed to perform request (connection was closed" +
                                                            " before response was received): " + ServerAddress);
                    });
                }
            }

            Dbg.WriteLine("Connection closed: " + ServerAddress);
        }
Exemplo n.º 7
0
        private static ReaderWriterLock _rwlock = new ReaderWriterLock();//定义一个读写锁
        /// <summary>
        /// 将指定的对象序列化到指定的文件
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="fullName">相对路径,含文件名</param>
        /// <returns></returns>
        public static bool SaveHistoryToFile(ChannelHistory[] obj, string path, string fileName)
        {
            bool bRet = false;

            try
            {
                //使用一个 System.Int32 超时值获取写线程锁。
                _rwlock.AcquireWriterLock(1000 * 60);
                path = Directory.GetCurrentDirectory() + @"\Data" + path;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path = path + fileName;
                BinaryFormatter bf = new BinaryFormatter();

                ////创建文件流
                using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
                {
                    //将对象数组序列化并保存到指定的文件中 F\:1.txt

                    bf.Serialize(fs, obj);
                    fs.Close();
                }
                //using (FileStream fss = new FileStream(path.Replace("dat", "txt"), FileMode.Append, FileAccess.Write))
                //{
                //    StreamWriter sw = new StreamWriter(fss);
                //    sw.WriteLine("------------------------------------------------------------");
                //    for (int i = 0; i < obj.Length; i++)
                //    {
                //        sw.WriteLine("Electricity:" + obj[i].Electricity + "|ActualDuration:" + obj[i].ActualDuration + "|CardNumber:" + obj[i].CardNumber + "|Duration:" + obj[i].Duration + "|Number:" + obj[i].Number + "|Ohm:" + obj[i].Ohm + "|QTime:" + obj[i].QTime + "|State:" + obj[i].State + "|Voltage:" + obj[i].Voltage);
                //    }
                //    sw.Close();
                //    fss.Close();
                //}
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                //减少写线程锁上的锁计数,释放写锁
                _rwlock.ReleaseWriterLock();
                // Model.PlayerModel._mu.ReleaseMutex();
            }

            return(bRet);
        }
Exemplo n.º 8
0
        public static void WriteToCSVFile(String pathToCSVFile, String username, String newFileName)
        {
            try
            {
                readerWriterLock.AcquireWriterLock(timeout);
                try
                {
                    string[] lines = new string[0];
                    lines = File.ReadAllLines(pathToCSVFile);

                    StringBuilder newLines  = new StringBuilder();
                    bool          userExist = false;

                    foreach (var line in lines)
                    {
                        string[] parts = line.Split(';');
                        if (parts.Length == 2 && parts[0].Equals(username))
                        {
                            parts[1] += "," + newFileName;
                            newLines.AppendLine(String.Format("{0};{1}", username, parts[1]));
                            userExist = true;
                        }
                        else
                        {
                            newLines.AppendLine(line.Trim());
                        }
                    }

                    if (!userExist)
                    {
                        newLines.AppendLine(String.Format("{0};{1}", username, newFileName));
                    }

                    File.WriteAllText(pathToCSVFile, newLines.ToString());
                }
                catch (ApplicationException ex)
                {
                    Console.WriteLine("[ERROR I/O] Access to file exception: " + ex);
                }
                finally
                {
                    readerWriterLock.ReleaseWriterLock();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[ERROR I/O] Write to file exception: " + ex);
            }
        }
Exemplo n.º 9
0
        public static void WriteDestination(string destinationFile, string sourceServer, IEnumerable <DestinationFile> files)
        {
            try
            {
                rwl.AcquireWriterLock(1000);
                using (XmlWriter xmlWriter = XmlWriter.Create(destinationFile))
                {
                    xmlWriter.WriteStartDocument();
                    xmlWriter.WriteStartElement("DeploymentInfo");

                    xmlWriter.WriteStartElement("Metadata");
                    xmlWriter.WriteAttributeString("Version", "1.5");
                    xmlWriter.WriteEndElement();

                    xmlWriter.WriteStartElement("Files");

                    foreach (var file in files)
                    {
                        xmlWriter.WriteStartElement("SourceFile");
                        xmlWriter.WriteAttributeString("name", file.SourceFile);
                        xmlWriter.WriteAttributeString("sourceServer", sourceServer);
                        xmlWriter.WriteAttributeString("sourceFolder", file.SourceFolder);

                        foreach (var targetFile in file.TargetFiles)
                        {
                            xmlWriter.WriteStartElement("TargetFile");
                            xmlWriter.WriteAttributeString("ServerType", targetFile.ServerType);
                            xmlWriter.WriteAttributeString("targetFolder", targetFile.TargetFolders.Aggregate((a, b) => a + ';' + b));
                            xmlWriter.WriteFullEndElement();
                        }

                        xmlWriter.WriteEndElement();

                        //todo
                    }
                    ;

                    xmlWriter.Close();
                }
            }
            catch
            {
                Console.WriteLine("Error while writing to xml");
            }
            finally
            {
                rwl.ReleaseWriterLock();
            }
        }
Exemplo n.º 10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="baseClass"></param>
        /// <param name="interfaces"></param>
        /// <returns></returns>
        public virtual Type GenerateCode(Type baseClass, Type[] interfaces)
        {
            Type type2;

            if (baseClass.IsSerializable)
            {
                this._delegateToBaseGetObjectData = this.VerifyIfBaseImplementsGetObjectData(baseClass);
                interfaces = this.AddISerializable(interfaces);
            }
            ReaderWriterLock rWLock = base.ModuleScope.RWLock;

            rWLock.AcquireReaderLock(-1);
            Type fromCache = base.GetFromCache(baseClass, interfaces);

            if (fromCache != null)
            {
                rWLock.ReleaseReaderLock();
                return(fromCache);
            }
            rWLock.UpgradeToWriterLock(-1);
            try
            {
                fromCache = base.GetFromCache(baseClass, interfaces);
                if (fromCache != null)
                {
                    return(fromCache);
                }
                this.CreateTypeBuilder(this.GenerateTypeName(baseClass, interfaces), baseClass, interfaces);
                this.GenerateFields();
                if (baseClass.IsSerializable)
                {
                    this.ImplementGetObjectData(interfaces);
                }
                this.ImplementCacheInvocationCache();
                base.GenerateTypeImplementation(baseClass, true);
                base.GenerateInterfaceImplementation(interfaces);
                this.GenerateConstructors(baseClass);
                if (this._delegateToBaseGetObjectData)
                {
                    this.GenerateSerializationConstructor();
                }
                type2 = this.CreateType();
            }
            finally
            {
                rWLock.ReleaseWriterLock();
            }
            return(type2);
        }
Exemplo n.º 11
0
 private static void WriteLockedMethod(
     ReaderWriterLock rwl,
     WriteLockMethod method
     )
 {
     rwl.AcquireWriterLock(0);
     try
     {
         method();
     }
     finally
     {
         rwl.ReleaseWriterLock();
     }
 }
Exemplo n.º 12
0
 public void LoadInstalledPackageDescriptions()
 {
     string[] pkgfiles = Directory.GetFiles(InstalledPackagesPath, "*.spkg");
     m_RwLock.AcquireWriterLock(-1);
     try
     {
         m_InstalledPackages.Clear();
         foreach (string pkgfile in pkgfiles)
         {
             using (var i = new FileStream(pkgfile, FileMode.Open))
             {
                 PackageDescription desc;
                 try
                 {
                     desc = new PackageDescription(i);
                 }
                 catch (Exception e)
                 {
                     throw new InvalidDataException("Failed to load package description " + pkgfile, e);
                 }
                 try
                 {
                     m_InstalledPackages.Add(desc.Name, desc);
                 }
                 catch
                 {
                     throw new ArgumentException(string.Format("Installed package {0} is duplicate in {1}.", desc.Name, pkgfile));
                 }
             }
         }
     }
     finally
     {
         m_RwLock.ReleaseWriterLock();
     }
 }
Exemplo n.º 13
0
        public bool Delete(int index)
        {
            var celebs = GetAll().ToList();

            var celeb = celebs.Where(c => c.Index == index).FirstOrDefault();

            if (celeb != null)
            {
                celebs.Remove(celeb);
                try
                {
                    readerWriterLock.AcquireWriterLock(lockTimeout_in_ms);
                    File.WriteAllText(celebs_json_path, JsonConvert.SerializeObject(celebs));
                }
                finally
                {
                    readerWriterLock.ReleaseWriterLock();
                }

                Logger.LogInformation("Deleted celeb with id " + index);
            }

            return(celeb != null);
        }
Exemplo n.º 14
0
        private void Consume()
        {
            try
            {
                if (_position == 0)
                {
                    return;
                }

                var nb = new byte[Length];

                _rwl.AcquireWriterLock(10000);
                Array.Copy(_data, _position, nb, 0, Length);
                _data = nb;
                _rwl.ReleaseWriterLock();

                _length   = _length - _position;
                _position = 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message, ex);
            }
        }
Exemplo n.º 15
0
        public void UnLock(long apTranId)
        {
            try {
                //Writerロックを取得する
                _rwLock.AcquireWriterLock(_timeout);

                if (_apTranId == apTranId)
                {
                    _apTranId = _nullApTranId;
                }
            } finally {
                //Writerロックを開放する
                _rwLock.ReleaseWriterLock();
            }
        }
Exemplo n.º 16
0
        private static async Task WriteToResource(string filename, string message)
        {
            _rwl.AcquireWriterLock(1000);
            try
            {
                File.AppendAllText(filename, message);
            }
            finally
            {
                // Ensure that the lock is released.
                _rwl.ReleaseWriterLock();
            }

            await Task.Delay(1);
        }
Exemplo n.º 17
0
        private void TakeScreenshot(bool captureMouse)
        {
            if (captureMouse)
            {
                var bmp = ScreenCapturePInvoke.CaptureFullScreen(true);
                rwl.AcquireWriterLock(Timeout.Infinite);
                bmp.Save(Application.StartupPath + "/WebServer" + "/ScreenTask.jpg", ImageFormat.Jpeg);
                rwl.ReleaseWriterLock();
                if (isPreview)
                {
                    img = new MemoryStream();
                    bmp.Save(img, ImageFormat.Jpeg);
                    imgPreview.Image = new Bitmap(img);
                }
                return;
            }
            Rectangle bounds = Screen.GetBounds(Point.Empty);

            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
                }
                rwl.AcquireWriterLock(Timeout.Infinite);
                bitmap.Save(Application.StartupPath + "/WebServer" + "/ScreenTask.jpg", ImageFormat.Jpeg);
                rwl.ReleaseWriterLock();

                if (isPreview)
                {
                    img = new MemoryStream();
                    bitmap.Save(img, ImageFormat.Jpeg);
                    imgPreview.Image = new Bitmap(img);
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Gets or sets the element at the specified index.
        /// </summary>
        /// <returns>
        /// The element at the specified index.
        ///   </returns>
        ///
        /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.
        ///   </exception>
        ///
        /// <exception cref="T:System.NotSupportedException">
        /// The property is set and the <see cref="T:System.Collections.Generic.IList`1"/> is read-only.
        ///   </exception>
        public T this[int index]
        {
            get
            {
                syncLock.AcquireReaderLock(Timeout.Infinite);
                T result = collection[index];
                syncLock.ReleaseReaderLock();
                return(result);
            }

            set
            {
                syncLock.AcquireWriterLock(Timeout.Infinite);

                if (collection.Count == 0 || collection.Count <= index)
                {
                    syncLock.ReleaseWriterLock();
                    return;
                }

                collection[index] = value;
                syncLock.ReleaseWriterLock();
            }
        }
Exemplo n.º 19
0
        public object AddEntry(string desc)
        {
            object key;

            aLock.AcquireWriterLock(TIMEOUT);
            try {
                addKey.Parameters["@value"].Value = desc;
                key = addKey.ExecuteScalar();
                key = findKey.ExecuteScalar();
            }
            finally {
                aLock.ReleaseWriterLock();
            }
            return(key);
        }
Exemplo n.º 20
0
        /// <summary>
        /// TCP状态消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTcpStatus(object sender, CTcpConArgs e)
        {
            try
            {
                _TCPLock.AcquireWriterLock(-1);

                if (!e.bErr)
                {
                    OnLogArgs.OnEvented(new CLogArgs(0, name, e.conStatus, (int)EResult.Action));
                }
                else
                {
                    OnLogArgs.OnEvented(new CLogArgs(0, name, e.conStatus, (int)EResult.NG));
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                _TCPLock.ReleaseWriterLock();
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Registers a factoryMethod as the method to be called to
        /// construct an object in reply to a request for typeRequested.
        /// </summary>
        /// <param name="typeRequested">The type requested (interface or base class).</param>
        /// <param name="factoryMethod">The factory method.</param>
        public void RegisterFactoryMethod(Type typeRequested, FactoryMethod factoryMethod)
        {
            #region Check preconditions
            if (typeRequested == null)
            {
                throw new ArgumentNullException("typeRequested");
            }

            if (factoryMethod == null)
            {
                throw new ArgumentNullException("factoryMethod");
            }
            #endregion Check preconditions

            rwlock.AcquireWriterLock(100);
            try
            {
                this.factoryMethods[typeRequested] = factoryMethod;
            }
            finally
            {
                rwlock.ReleaseWriterLock();
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// 解除写入锁
 /// </summary>
 /// <param name="rwlock">读写锁</param>
 /// <param name="ilc">Cookie对象</param>
 public static void ReleaseWriterLock(ReaderWriterLock rwlock, IntelligentLockCookie ilc)
 {
     if (true == ilc.locked)
     {
         if (true == ilc.upgrade)
         {
             LockCookie lc = ilc.lc;
             rwlock.DowngradeFromWriterLock(ref lc);
         }
         else
         {
             rwlock.ReleaseWriterLock();
         }
     }
 }
Exemplo n.º 23
0
        /// <summary>
        /// Tear down the endpoint gracefully
        /// </summary>
        private void CleanupMCS()
        {
            shutdownLock.AcquireWriterLock(Timeout.Infinite);
            shutdownLock.ReleaseWriterLock();

            // Clean-up the browser
            this.CleanupBrowser();
            // Clean-up the call
            this.CleanupCall();

            if (endpoint != null)
            {
                endpoint.EndTerminate(endpoint.BeginTerminate(null, null));
            }
        }
Exemplo n.º 24
0
 private static void LogToFile(LogMessage logMessage)
 {
     try
     {
         Locker.AcquireWriterLock(int.MaxValue);
         File.AppendAllLines(LogPath, new List <string>()
         {
             logMessage.ToJson()
         });
     }
     finally
     {
         Locker.ReleaseWriterLock();
     }
 }
Exemplo n.º 25
0
        public static void WriteDebug(string text)
        {
            try
            {
                locker.AcquireWriterLock(int.MaxValue); //You might wanna change timeout value
                StreamWriter  log;
                FileStream    fileStream = null;
                DirectoryInfo logDirInfo = null;
                FileInfo      logFileInfo;

                string logFilePath = Environment.CurrentDirectory + "\\Logs\\";
                logFilePath = logFilePath + DateTime.Today.ToString("dd-MM-yyyy") + "-debug." + "txt";
                logFileInfo = new FileInfo(logFilePath);
                logDirInfo  = new DirectoryInfo(logFileInfo.DirectoryName);
                if (!logDirInfo.Exists)
                {
                    logDirInfo.Create();
                }
                if (!logFileInfo.Exists)
                {
                    fileStream = logFileInfo.Create();
                }
                else
                {
                    fileStream = new FileStream(logFilePath, FileMode.Append);
                }

                log = new StreamWriter(fileStream);
                log.WriteLine(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss.fff tt\t") + text);
                log.Close();
            }
            finally
            {
                locker.ReleaseWriterLock();
            }
        }
Exemplo n.º 26
0
        public virtual object Request()
        {
            rwlock.AcquireWriterLock(-1);

            object instance = null;

            try
            {
                if (available.Count != 0)
                {
                    instance = available.Pop();

                    if (instance == null)
                    {
                        throw new PoolException("Invalid instance on the pool stack");
                    }
                }
                else
                {
                    instance = componentActivator.Create();

                    if (instance == null)
                    {
                        throw new PoolException("Activator didn't return a valid instance");
                    }
                }

                inUse.Add(instance);
            }
            finally
            {
                rwlock.ReleaseWriterLock();
            }

            return(instance);
        }
Exemplo n.º 27
0
 public bool AttachLogTarget(ILogTarget logTarget)
 {
     try
     {
         rwlLogTargetList.AcquireWriterLock(Timeout.Infinite);
         try
         {
             allLogTarget.Add(logTarget);
             return(true);
         }
         catch
         {
             return(false);
         }
         finally
         {
             rwlLogTargetList.ReleaseWriterLock();
         }
     }
     catch
     {
         return(false);
     }
 }
Exemplo n.º 28
0
        /// <summary/>
        /// <param name="message"/>
        /// <exclude/>
        protected void FireEvent(string message)
        {
            writerLock.AcquireWriterLock(LockTimeout);
            try
            {
                eventMessage = message;
                InstrumentedEvent.FireWmiEvent(this);
            }
            finally
            {
                writerLock.ReleaseWriterLock();
            }

            FireAuxEvent(string.Empty);
        }
Exemplo n.º 29
0
 public void Dispose()
 {
     if (_accessMode == AccessMode.Read)
     {
         _rwLock.ReleaseReaderLock();
     }
     else if (_accessMode == AccessMode.Write)
     {
         _rwLock.ReleaseWriterLock();
     }
     else //UpAndDowngrade
     {
         _rwLock.DowngradeFromWriterLock(ref _lockCookie);
     }
 }
Exemplo n.º 30
0
        internal void DisposeInternal(bool removeTopic)
        {
            try
            {
                _readerWriterLock.AcquireWriterLock(Timeout.Infinite);
                if (_isDisposed)
                {
                    return;
                }

                if (_refCount > 0)
                {
                    Interlocked.Decrement(ref _refCount);
                }
                if (removeTopic)
                {
                    Interlocked.Exchange(ref _refCount, 0);
                }

                if (_refCount == 0 && !_isDisposed)
                {
                    if (_subscriptions != null)
                    {
                        lock (_subscriptions)
                        {
                            foreach (KeyValuePair <string, TopicSubscription> pair in _subscriptions)
                            {
                                pair.Value.Dispose();
                            }

                            _subscriptions.Clear();
                        }
                    }

                    if (HasFailureDeliveryNotification)
                    {
                        _cacheImpl.UnSubscribe(_topicName, _publisherId, SubscriptionType.Publisher);
                    }
                    _messageDeliveryFailure = null;
                    _subscriptions          = null;
                    _isDisposed             = true;
                }
            }
            finally
            {
                _readerWriterLock.ReleaseWriterLock();
            }
        }