本文整理汇总了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();
}
示例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;
}
示例3: CompositionLock
public CompositionLock(bool isThreadSafe)
{
this._isThreadSafe = isThreadSafe;
if (isThreadSafe)
{
this._stateLock = new Lock();
}
}
示例4: Release
public void Release(Lock @lock)
{
lock (this) {
locks.Remove(@lock);
Lockable.Released(@lock);
Monitor.PulseAll(this);
}
}
示例5: NewLock
public Lock NewLock(LockingMode mode, AccessType accessType)
{
lock (this) {
var @lock = new Lock(this, mode, accessType);
Acquire(@lock);
@lock.OnAcquired();
return @lock;
}
}
示例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";
}
}
示例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();
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
}
示例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);
}
}
}
示例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]));
}
示例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]));
}