当前位置: 首页>>代码示例>>C#>>正文


C# Lock类代码示例

本文整理汇总了C#中Lock的典型用法代码示例。如果您正苦于以下问题:C# Lock类的具体用法?C# Lock怎么用?C# Lock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Lock类属于命名空间,在下文中一共展示了Lock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: RepositoryCache

 public RepositoryCache()
 {
     cacheMap = new Dictionary<Key, WeakReference<Repository>>();
     openLocks = new Lock[4];
     for (int i = 0; i < openLocks.Length; i++)
         openLocks[i] = new Lock();
 }
开发者ID:spraints,项目名称:GitSharp,代码行数:7,代码来源:RepositoryCache.cs

示例2: Lock

 public bool Lock(RedisKey resource, TimeSpan ttl, out Lock lockObject)
 {
     var task = LockAsync(resource, ttl);
     task.Wait();
     var result = task.Result;
     lockObject = result.Item2;
     return result.Item1;
 }
开发者ID:collinsauve,项目名称:redlock-cs,代码行数:8,代码来源:Redlock.cs

示例3: CompositionLock

 public CompositionLock(bool isThreadSafe)
 {
     this._isThreadSafe = isThreadSafe;
     if (isThreadSafe)
     {
         this._stateLock = new Lock();
     }
 }
开发者ID:nlhepler,项目名称:mono,代码行数:8,代码来源:CompositionLock.cs

示例4: Release

 public void Release(Lock @lock)
 {
     lock (this) {
         locks.Remove(@lock);
         Lockable.Released(@lock);
         Monitor.PulseAll(this);
     }
 }
开发者ID:deveel,项目名称:deveeldb,代码行数:8,代码来源:LockingQueue.cs

示例5: NewLock

 public Lock NewLock(LockingMode mode, AccessType accessType)
 {
     lock (this) {
         var @lock = new Lock(this, mode, accessType);
         Acquire(@lock);
         @lock.OnAcquired();
         return @lock;
     }
 }
开发者ID:deveel,项目名称:deveeldb,代码行数:9,代码来源:LockingQueue.cs

示例6: Create

		/// <summary>
		/// Try to aquire a machine-wide lock named 'name'. Returns null in case of failure (it doesn't wait at all).
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		public static Lock Create (string name)
		{
			Lock result = new Lock ();
			Mutex mutex;
			Semaphore semaphore;

			switch (Configuration.LockingAlgorithm.ToLowerInvariant ()) {
			case "mutex":
				mutex = new Mutex (true, name);
				if (mutex.WaitOne (1 /* ms */)) {
					result.mutex = mutex;
					return result;
				}
				return null;
			case "file":
				try {
					result.file = File.Open (Path.Combine (Path.GetTempPath (), name + ".lock"), FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
					return result;
				} catch (IOException ex) {
					Logger.Log ("Could not aquire builder lock: {0}", ex.Message);
					return null;
				}
			case "fileexistence":
			case "fileexistance":
				string tmp = Path.Combine (Path.GetTempPath (), name + ".fileexistence-lock--delete-to-unlock");
				Logger.Log ("Checking file existence for {0}", tmp);
				if (File.Exists (tmp)) {
					try {
						if (ProcessHelper.Exists (int.Parse (File.ReadAllText (tmp)))) {
							Logger.Log ("File lock corresponds to an existing process.");
							return null;
						}
					} catch (Exception ex) {
						Logger.Log ("Could not confirm that file lock corresponds to a non-existing process: {0}", ex.Message);
						return null;
					}
					Logger.Log ("File lock corresponds to a dead process, lock acquired");
				}
				// there is a race condition here.
				// given that the default setup is to execute a program at most once per minute,
				// the race condition is harmless.
				File.WriteAllText (tmp, Process.GetCurrentProcess ().Id.ToString ());
				result.file_existence = tmp;
				return result;
			case "semaphore":
				semaphore = new Semaphore (1, 1, name);
				if (semaphore.WaitOne (1 /* ms */)) {
					result.semaphore = semaphore;
					return result;
				}
				return null;
			default:
				Logger.Log ("Unknown locking algorithm: {0} (using default 'semaphore')", Configuration.LockingAlgorithm);
				goto case "semaphore";
			}
		}
开发者ID:hackmp,项目名称:monkeywrench,代码行数:61,代码来源:Lock.cs

示例7: SEMA4

 public SEMA4(Machine machine)
 {
     sysbus = machine.SystemBus;
     irqLock = new object();
     locks = new Lock[NumberOfEntries];
     for(var i = 0; i < locks.Length; i++)
     {
         locks[i] =  new Lock(this, i);
     }
     CPU0 = new GPIO();
     CPU1 = new GPIO();
 }
开发者ID:rte-se,项目名称:emul8,代码行数:12,代码来源:SEMA4.cs

示例8: GetInstanceOfLock

        private static MCS.Library.SOA.DataObjects.Lock GetInstanceOfLock(string lockId, IUser user)
        {
            Lock _lock = new Lock();

            _lock.LockID = lockId;
            _lock.LockTime = DateTime.Now;
            _lock.LockType = LockType.ActivityLock;
            double db = 0.0;
            _lock.EffectiveTime = TimeSpan.FromMinutes(db);
            _lock.PersonID = user.ID;

            return _lock;
        }
开发者ID:jerryshi2007,项目名称:AK47Source,代码行数:13,代码来源:LockTest.cs

示例9: GetLock

 public bool GetLock(DataLocation dataLocation)
 {
     lock (_locks)
     {
         if (_locks.Any(takenLock => takenLock.Overlap(dataLocation)))
         {
             return false;
         }
         Lock newLock = new Lock(dataLocation);
         _locks.Add(newLock);
     }
     return true;
 }
开发者ID:glenwatson,项目名称:Distributed-Database,代码行数:13,代码来源:LockManager.cs

示例10: Lock

        public bool Lock(RedisKey resource, TimeSpan ttl, out Lock lockObject)
        {
            var val = CreateUniqueLockId();
            Lock innerLock = null;
            bool successfull = retry(DefaultRetryCount, DefaultRetryDelay, () =>
            {
                try
                {
                    int n = 0;
                    var startTime = DateTime.Now;

                    // Use keys
                    for_each_redis_registered(
                        redis =>
                        {
                            if (LockInstance(redis, resource, val, ttl)) n += 1;
                        }
                    );

                    /*
                     * Add 2 milliseconds to the drift to account for Redis expires
                     * precision, which is 1 milliescond, plus 1 millisecond min drift
                     * for small TTLs.
                     */
                    var drift = Convert.ToInt32((ttl.TotalMilliseconds * ClockDriveFactor) + 2);
                    var validity_time = ttl - (DateTime.Now - startTime) - new TimeSpan(0, 0, 0, 0, drift);

                    if (n >= Quorum && validity_time.TotalMilliseconds > 0)
                    {
                        innerLock = new Lock(resource, val, validity_time);
                        return true;
                    }
                    else
                    {
                        for_each_redis_registered(
                            redis =>
                            {
                                UnlockInstance(redis, resource, val);
                            }
                        );
                        return false;
                    }
                }
                catch (Exception)
                { return false; }
            });

            lockObject = innerLock;
            return successfull;
        }
开发者ID:renaatd,项目名称:redlock-cs,代码行数:50,代码来源:Redlock.cs

示例11: DisposableWrapperCatalog

		public DisposableWrapperCatalog(ComposablePartCatalog innerCatalog, bool isThreadSafe)
		{
			if (innerCatalog == null)
				throw new ArgumentNullException(nameof(innerCatalog));

			_lock = new Lock(isThreadSafe, LockRecursionPolicy.NoRecursion);
			_cache = new Dictionary<ComposablePartDefinition, ComposablePartDefinition>();
			_innerCatalog = innerCatalog;
			_compositionOrigin = innerCatalog as ICompositionElement;

			var notify = innerCatalog as INotifyComposablePartCatalogChanged;
			if (notify == null) return;

			notify.Changed += OnChanged;
			notify.Changing += OnChanging;
		}
开发者ID:polewskm,项目名称:NCode.Composition.DisposableParts,代码行数:16,代码来源:DisposableWrapperCatalog.cs

示例12: CheckAccess

        internal void CheckAccess(Lock @lock)
        {
            lock (this) {
                // Error checking.  The queue must contain the Lock.
                if (!locks.Contains(@lock))
                    throw new InvalidOperationException("Queue does not contain the given Lock");

                // If 'READ'
                bool blocked;
                int index;
                if (@lock.AccessType == AccessType.Read) {
                    do {
                        blocked = false;

                        index = locks.IndexOf(@lock);

                        int i;
                        for (i = index - 1; i >= 0 && !blocked; --i) {
                            var testLock = locks[i];
                            if (testLock.AccessType == AccessType.Write)
                                blocked = true;
                        }

                        if (blocked) {
                            Monitor.Wait(this);
                        }
                    } while (blocked);
                } else {
                    do {
                        blocked = false;

                        index = locks.IndexOf(@lock);

                        if (index != 0) {
                            blocked = true;

                            Monitor.Wait(this);
                        }

                    } while (blocked);
                }

                // Notify the Lock table that we've got a lock on it.
                // TODO: Lock.Table.LockAcquired(Lock);
            }
        }
开发者ID:prepare,项目名称:deveeldb,代码行数:46,代码来源:LockingQueue.cs

示例13: Process

 public override void Process()
 {
     DCTSimpleProperty property = DataProperty as DCTSimpleProperty;
     if (null != property)
     {
         var containerElement = document.MainDocumentPart.Document.Body
         .Descendants<SdtElement>().Where(o => o.SdtProperties.Descendants<SdtAlias>().Any(a => a.Val == DataProperty.TagID)).FirstOrDefault();
         if (null == containerElement)
             return;
         var runElement = containerElement.Descendants<Run>().First();
         runElement.RemoveAllChildren();
         runElement.AppendChild<Text>(new Text(GeneralFormatter.ToString(property.Value, property.FormatString)));
         if (property.IsReadOnly)
         {
             Lock lockControl = new Lock();
             lockControl.Val = LockingValues.SdtContentLocked;
             containerElement.SdtProperties.Append(lockControl);
         }
     }
 }
开发者ID:jerryshi2007,项目名称:AK47Source,代码行数:20,代码来源:GeneralDataProcessor.cs

示例14: case_1008

void case_1008()
#line 6738 "cs-parser.jay"
{
		if (yyVals[0+yyTop] is EmptyStatement && lexer.peek_token () == Token.OPEN_BRACE)
			Warning_EmptyStatement (GetLocation (yyVals[0+yyTop]));
	  
		yyVal = new Lock ((Expression) yyVals[-2+yyTop], (Statement) yyVals[0+yyTop], GetLocation (yyVals[-4+yyTop]));
		lbag.AddStatement (yyVal, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop]));
	  }
开发者ID:furesoft,项目名称:NRefactory,代码行数:9,代码来源:cs-parser.cs

示例15: case_1009

void case_1009()
#line 6746 "cs-parser.jay"
{
		Error_SyntaxError (yyToken);

		yyVal = new Lock ((Expression) yyVals[-1+yyTop], null, GetLocation (yyVals[-3+yyTop]));
		lbag.AddStatement (yyVal, GetLocation (yyVals[-2+yyTop]));
	  }
开发者ID:furesoft,项目名称:NRefactory,代码行数:8,代码来源:cs-parser.cs


注:本文中的Lock类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。