public async Task Lock_OneShot() { const string keyName = "test/lock/oneshot"; var lockOptions = new LockOptions(keyName) { LockTryOnce = true }; Assert.Equal(Lock.DefaultLockWaitTime, lockOptions.LockWaitTime); lockOptions.LockWaitTime = TimeSpan.FromMilliseconds(1000); var lockKey = _client.CreateLock(lockOptions); await lockKey.Acquire(CancellationToken.None); var contender = _client.CreateLock(new LockOptions(keyName) { LockTryOnce = true, LockWaitTime = TimeSpan.FromMilliseconds(1000) }); var stopwatch = Stopwatch.StartNew(); Assert.True(lockKey.IsHeld); Assert.False(contender.IsHeld); await TimeoutUtils.WithTimeout( Assert.ThrowsAsync <LockMaxAttemptsReachedException>(async() => await contender.Acquire())); Assert.False(stopwatch.ElapsedMilliseconds < lockOptions.LockWaitTime.TotalMilliseconds); Assert.False(contender.IsHeld, "Contender should have failed to acquire"); Assert.True(lockKey.IsHeld); Assert.False(contender.IsHeld); await lockKey.Release(); Assert.False(lockKey.IsHeld); Assert.False(contender.IsHeld); while (contender.IsHeld == false) { try { await contender.Acquire(); Assert.False(lockKey.IsHeld); Assert.True(contender.IsHeld); } catch (LockMaxAttemptsReachedException) { // Ignore because lock delay might be in effect. } } await contender.Release(); await contender.Destroy(); }
public async Task Lock_TryAcquireOnceWithLockDelayNonZeroWaitTime_EnsureRetryWait() { const string keyName = "test/lock/acquireoncewithlockdelay_ensureretrywait"; var lockKey = (Lock)_client.CreateLock(keyName); await lockKey.Acquire(CancellationToken.None); Assert.True(lockKey.IsHeld); await _client.Session.Destroy(lockKey.LockSession); var oneShotLockOptions = new LockOptions(keyName) { LockTryOnce = true, LockWaitTime = TimeSpan.FromSeconds(1), LockRetryTime = TimeSpan.FromSeconds(5) }; var oneShotLock = (Lock)_client.CreateLock(oneShotLockOptions); var stopwatch = Stopwatch.StartNew(); await Assert.ThrowsAsync <LockMaxAttemptsReachedException>( async() => await oneShotLock.Acquire(CancellationToken.None)); var elapsedMilliseconds = stopwatch.ElapsedMilliseconds; Assert.False(oneShotLock.IsHeld); // https://github.com/dotnet/runtime/issues/45585 Assert.True(elapsedMilliseconds > oneShotLockOptions.LockRetryTime.TotalMilliseconds * 0.9); }
public async Task Lock_AcquireWaitRelease() { var client = new ConsulClient(); const string keyName = "test/lock/acquirewaitrelease"; var lockOptions = new LockOptions(keyName) { SessionName = "test_locksession", SessionTTL = TimeSpan.FromSeconds(10) }; var l = client.CreateLock(lockOptions); await l.Acquire(CancellationToken.None); Assert.True(l.IsHeld); // Wait for multiple renewal cycles to ensure the lock session stays renewed. Task.Delay(TimeSpan.FromSeconds(60)).Wait(); Assert.True(l.IsHeld); await l.Release(); Assert.False(l.IsHeld); await l.Destroy(); }
public static LockOptions FindAtomicIsLockedStatusReplicated(RspList results, ref object lockId, ref DateTime lockDate) { LockOptions lockInfo = null; if (results == null) { return(lockInfo); } for (int i = 0; i < results.size(); i++) { Rsp rsp = (Rsp)results.elementAt(i); if (rsp.wasSuspected()) { continue; } if (!rsp.wasReceived()) { continue; } lockInfo = (LockOptions)rsp.Value; if (lockInfo != null) { if (lockInfo.LockId != null) { return(lockInfo); } } } return(lockInfo); }
internal protected override IQueryable <TEntity> CreateEntitySet <TEntity>(LockOptions lockOptions) { QueryPredicate <TEntity> authFilter = null; // We allow to execute LINQ queries in elevated mode if (!ReadUnrestricted) { //Check access rights var entInfo = GetEntityInfo(typeof(TEntity)); UserEntityTypePermission typePermissions; // CheckEntityAccess will throw AccessDenied if DenyReadAction is Throw; if it is Filter, we just return empty list if (!CheckEntityAccess(entInfo, _demandReadAccessType, out typePermissions)) { return(new List <TEntity>().AsQueryable()); //return empty list } //read predicate filter from Authority authFilter = this.Context.User.Authority.GetQueryFilter <TEntity>(); } IQueryable <TEntity> entSet = base.CreateEntitySet <TEntity>(lockOptions); //base entSet already includes predicate from Context.QueryFilter (if there is one) // We now add predicate from authorization if (authFilter == null) { return(entSet); } else { return(entSet.Where(authFilter.Where)); } }
}//method private void RunTests(LockOptions readOptions, LockOptions writeOptions, int threadCount = 10, int readWriteCount = 50) { // delete old data and create 5 docs Startup.DeleteAll(_app); var session = _app.OpenSession(); for (int i = 0; i < 5; i++) { var iDoc = session.NewEntity <IDoc>(); iDoc.Name = "D" + i; } session.SaveChanges(); var docIds = session.GetEntities <IDoc>(take: 10).Select(d => d.Id).ToArray(); // clear error counts, _updateErrorCount = 0; _sumErrorCount = 0; // create multiple threads and start reading/writing Task[] tasks = new Task[threadCount]; for (int i = 0; i < threadCount; i++) { tasks[i] = Task.Run(() => RunRandomReadWriteOp(docIds, readOptions, writeOptions, readWriteCount)); } Task.WaitAll(tasks); }
public async Task Lock_AcquireWaitRelease() { const string keyName = "test/lock/acquirewaitrelease"; var lockOptions = new LockOptions(keyName) { SessionName = "test_locksession", SessionTTL = TimeSpan.FromSeconds(10) }; var l = _client.CreateLock(lockOptions); await l.Acquire(CancellationToken.None); Assert.True(l.IsHeld); // Wait for multiple renewal cycles to ensure the semaphore session stays renewed. for (int i = 0; i < 60; i++) { await Task.Delay(1000); Assert.True(l.IsHeld); } Assert.True(l.IsHeld); await l.Release(); Assert.False(l.IsHeld); await l.Destroy(); }
public TableExpression(Type type, string name, DbTableInfo tableInfo, LockOptions lockOptions = LockOptions.None) : base(SqlExpressionType.Table, type) { Vita.Common.Util.Check(type != null, "TableExpression (name: {0}) - type may not be null.", name); TableInfo = tableInfo; Name = name; LockOptions = lockOptions; }
public TableExpression(DbTableInfo tableInfo, Type type, string name, LockOptions lockOptions = LockOptions.None) : base(SqlExpressionType.Table, type) { Vita.Common.Util.Check(type != null, "TableExpression (name: {0}) - type may not be null.", name); TableInfo = tableInfo; Name = name; LockOptions = lockOptions; }
public void Lock_OneShot() { var client = new ConsulClient(); const string keyName = "test/lock/oneshot"; var lockOptions = new LockOptions(keyName) { LockTryOnce = true }; Assert.Equal(Lock.DefaultLockWaitTime, lockOptions.LockWaitTime); lockOptions.LockWaitTime = TimeSpan.FromMilliseconds(1000); var lockKey = client.CreateLock(lockOptions); lockKey.Acquire(CancellationToken.None); var contender = client.CreateLock(new LockOptions(keyName) { LockTryOnce = true, LockWaitTime = TimeSpan.FromMilliseconds(1000) }); var stopwatch = Stopwatch.StartNew(); Exception didExcept = null; Task.WaitAny( Task.Run(() => { // Needed because async asserts don't work in sync methods! try { contender.Acquire(); } catch (Exception e) { didExcept = e; } }), Task.Delay((int)(2 * lockOptions.LockWaitTime.TotalMilliseconds)).ContinueWith((t) => Assert.True(false, "Took too long")) ); Assert.False(stopwatch.ElapsedMilliseconds < lockOptions.LockWaitTime.TotalMilliseconds); Assert.False(contender.IsHeld, "Contender should have failed to acquire"); Assert.IsType <LockMaxAttemptsReachedException>(didExcept); lockKey.Release(); contender.Acquire(); Assert.True(contender.IsHeld); contender.Release(); contender.Destroy(); }
public void Lock_OneShot() { var client = new ConsulClient(); const string keyName = "test/lock/oneshot"; var lockOptions = new LockOptions(keyName) { LockTryOnce = true }; Assert.Equal(Lock.DefaultLockWaitTime, lockOptions.LockWaitTime); lockOptions.LockWaitTime = TimeSpan.FromMilliseconds(1000); var lockKey = client.CreateLock(lockOptions); lockKey.Acquire(CancellationToken.None); var contender = client.CreateLock(new LockOptions(keyName) { LockTryOnce = true, LockWaitTime = TimeSpan.FromMilliseconds(1000) }); var stopwatch = Stopwatch.StartNew(); Exception didExcept = null; Task.WaitAny( Task.Run(() => { // Needed because async asserts don't work in sync methods! try { contender.Acquire(); } catch (Exception e) { didExcept = e; } }), Task.Delay((int)(2 * lockOptions.LockWaitTime.TotalMilliseconds)).ContinueWith((t) => Assert.True(false, "Took too long")) ); Assert.False(stopwatch.ElapsedMilliseconds < lockOptions.LockWaitTime.TotalMilliseconds); Assert.False(contender.IsHeld, "Contender should have failed to acquire"); Assert.IsType<LockMaxAttemptsReachedException>(didExcept); lockKey.Release(); contender.Acquire(); Assert.True(contender.IsHeld); contender.Release(); contender.Destroy(); }
static async Task <int> CommandLock([NotNull] LockOptions lockOptions, [NotNull] IDistributedMutexClient distributedMutexClient, [NotNull] ISnapFilesystem filesystem, [NotNull] ISnapAppReader appReader, [NotNull] ILog logger, [NotNull] string workingDirectory, CancellationToken cancellationToken) { if (lockOptions == null) { throw new ArgumentNullException(nameof(lockOptions)); } if (distributedMutexClient == null) { throw new ArgumentNullException(nameof(distributedMutexClient)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (workingDirectory == null) { throw new ArgumentNullException(nameof(workingDirectory)); } var snapApps = BuildSnapAppsFromDirectory(filesystem, appReader, workingDirectory); var snapApp = snapApps.Apps.FirstOrDefault(x => string.Equals(x.Id, lockOptions.Id, StringComparison.OrdinalIgnoreCase)); if (snapApp == null) { logger.Error($"Unable to find application with id: {lockOptions.Id}."); return(1); } MaybeOverrideLockToken(snapApps, logger, lockOptions.Id, lockOptions.Token, "--token"); if (string.IsNullOrWhiteSpace(snapApps.Generic.Token)) { logger.Error("Please specify a token in your snapx.yml file. A random UUID is sufficient."); return(1); } await using var distributedMutex = WithDistributedMutex(distributedMutexClient, logger, snapApps.BuildLockKey(snapApp), cancellationToken, false); bool success; if (!lockOptions.Release) { success = await distributedMutex.TryAquireAsync(); return(success ? 0 : 1); } success = await DistributedMutex.TryForceReleaseAsync(distributedMutex.Name, distributedMutexClient, logger); return(success ? 0 : 1); }
/// <summary> /// 需要先初始化 /// </summary> /// <param name="key"></param> public Task <IDistributedLock> AcquireLock(string key) { LockOptions opts = new LockOptions($"{prefix}{key}");//默认值 //{ // LockRetryTime = TimeSpan.FromSeconds(5), // LockWaitTime = TimeSpan.FromSeconds(3), // MonitorRetryTime = TimeSpan.FromSeconds(1) //}; return(this.consulClient.AcquireLock(opts)); }
/// <summary> /// 包装了一层,委托嵌套 /// </summary> /// <param name="key"></param> /// <param name="action"></param> /// <returns></returns> public Task ExecuteLocked(string key, Action action) { //Console.WriteLine($"{prefix}{key}"); LockOptions opts = new LockOptions($"{prefix}{key}");//默认值 //{ // LockRetryTime = TimeSpan.FromSeconds(5), // LockWaitTime = TimeSpan.FromSeconds(3), // MonitorRetryTime = TimeSpan.FromSeconds(1) //}; return(this.consulClient.ExecuteLocked(opts, action)); }
private IBookOrder GetOpenOrder(IEntitySession session, LockOptions lockOptions, bool create = false) { var currUserId = Context.User.UserId; var openOrder = session.EntitySet <IBookOrder>(lockOptions) .Where(bo => bo.User.Id == currUserId && bo.Status == OrderStatus.Open).FirstOrDefault(); if (openOrder == null && create) { var user = session.GetEntity <IUser>(Context.User.UserId); openOrder = session.NewOrder(user); } return(openOrder); }
internal Lock(ConsulClient _client, LockOptions _o, IDistributedLock _lck, CancellationToken _ct) { this._client = _client; this._o = _o; this._ct = _ct; this._lck = _lck; if (_lck.IsHeld) { LockAtTime = DateTime.Now; } if (!_ct.IsCancellationRequested) { _d = _ct.Register(o => ((Lock)o).Dispose(), this, false); } }
public async Task <ILock> LockAsync(string ck, int ttl = 5000, int retry = 2, int retryDelay = 1000) { var id = Guid.NewGuid(); var o = new LockOptions(ck) { Value = id.ToByteArray(), SessionName = id.ToString("n"), SessionTTL = TimeSpan.FromMilliseconds(ttl), LockRetryTime = TimeSpan.FromMilliseconds(retryDelay), LockWaitTime = TimeSpan.FromMilliseconds(retry * retryDelay), }; var lck = _client.CreateLock(o); var ct = await lck.Acquire(CancellationToken.None).ConfigureAwait(false); return(new Lock(_client, o, lck, ct)); }
internal protected virtual IQueryable <TEntity> CreateEntitySet <TEntity>(LockOptions lockOptions) where TEntity : class { var entInfo = GetEntityInfo(typeof(TEntity)); var prov = new EntityQueryProvider(this); var entSet = new EntitySet <TEntity>(prov, lockOptions); //Check filters var pred = Context.QueryFilter.GetPredicate <TEntity>(); if (pred != null) { return(entSet.Where(pred.Where)); } else { return(entSet); } }
/// <summary> /// Initializes a new instance of the <see cref="AutoSetupMiddleware"/> class. /// </summary> /// <param name="next">The next middleware in the execution pipeline.</param> /// <param name="shellHost">The shell host.</param> /// <param name="shellSettings">The shell settings.</param> /// <param name="shellSettingsManager">The shell settings manager.</param> /// <param name="distributedLock">The distributed lock.</param> /// <param name="options">The auto setup options.</param> /// <param name="logger">The logger.</param> public AutoSetupMiddleware( RequestDelegate next, IShellHost shellHost, ShellSettings shellSettings, IShellSettingsManager shellSettingsManager, IDistributedLock distributedLock, IOptions <AutoSetupOptions> options, ILogger <AutoSetupMiddleware> logger) { _next = next; _shellHost = shellHost; _shellSettings = shellSettings; _shellSettingsManager = shellSettingsManager; _distributedLock = distributedLock; _options = options.Value; _logger = logger; _lockOptions = _options.LockOptions; _setupOptions = _options.Tenants.FirstOrDefault(options => _shellSettings.Name == options.ShellName); }
public void Lock_OneShot() { var client = new ConsulClient(); const string keyName = "test/lock/oneshot"; var lockOptions = new LockOptions(keyName) { LockTryOnce = true }; Assert.Equal(Lock.DefaultLockWaitTime, lockOptions.LockWaitTime); lockOptions.LockWaitTime = TimeSpan.FromMilliseconds(250); var lockKey = client.CreateLock(lockOptions); lockKey.Acquire(CancellationToken.None); var contender = client.CreateLock(new LockOptions(keyName) { LockTryOnce = true, LockWaitTime = TimeSpan.FromMilliseconds(250) }); Task.WaitAny(Task.Run(() => { Assert.Throws <LockMaxAttemptsReachedException>(() => contender.Acquire() ); }), Task.Delay(2 * lockOptions.LockWaitTime.Milliseconds).ContinueWith((t) => Assert.True(false, "Took too long")) ); lockKey.Release(); contender.Acquire(); contender.Release(); contender.Destroy(); }
public void Lock_OneShot() { var client = new ConsulClient(); const string keyName = "test/lock/oneshot"; var lockOptions = new LockOptions(keyName) { LockTryOnce = true }; Assert.Equal(Lock.DefaultLockWaitTime, lockOptions.LockWaitTime); lockOptions.LockWaitTime = TimeSpan.FromMilliseconds(250); var lockKey = client.CreateLock(lockOptions); lockKey.Acquire(CancellationToken.None); var contender = client.CreateLock(new LockOptions(keyName) { LockTryOnce = true, LockWaitTime = TimeSpan.FromMilliseconds(250) }); Task.WaitAny(Task.Run(() => { Assert.Throws<LockMaxAttemptsReachedException>(() => contender.Acquire() ); }), Task.Delay(2 * lockOptions.LockWaitTime.Milliseconds).ContinueWith((t) => Assert.True(false, "Took too long")) ); lockKey.Release(); contender.Acquire(); contender.Release(); contender.Destroy(); }
public override void Initialize(AppModuleContext context) { base.Initialize(context); LockOptions lockOption = null; if (AppConfig.Configuration != null) { lockOption = AppConfig.Configuration.Get <LockOptions>(); } else { var lockSection = SurgingAppConfig.Configuration.GetSection("Lock"); if (lockSection.Exists()) { lockOption = lockSection.Get <LockOptions>(); } } if (lockOption == null) { throw new CPlatformException("请添加分布式锁服务设置"); } AppConfig.LockOption = lockOption; }
public virtual TableExpression CreateTable(Type tableType, TranslationContext context, LockOptions lockOptions = LockOptions.None) { var tableInfo = _dbModel.GetTable(tableType); var tableExpr = new TableExpression(tableType, tableInfo.FullName, tableInfo, lockOptions); return tableExpr; }
public TableExpression(DbTableInfo tableInfo, LockOptions lockOptions = LockOptions.None) : this(tableInfo, tableInfo.Entity.EntityType, tableInfo.FullName, lockOptions) { }
public void Lock_AcquireWaitRelease() { var lockOptions = new LockOptions("test/lock") { SessionName = "test_locksession", SessionTTL = TimeSpan.FromSeconds(10) }; var c = ClientTest.MakeClient(); var l = c.CreateLock(lockOptions); l.Acquire(CancellationToken.None); Assert.IsTrue(l.IsHeld); // Wait for multiple renewal cycles to ensure the lock session stays renewed. Task.Delay(TimeSpan.FromSeconds(60)).Wait(); Assert.IsTrue(l.IsHeld); l.Release(); Assert.IsFalse(l.IsHeld); l.Destroy(); }
public void Lock_AcquireWaitRelease() { var client = new ConsulClient(); const string keyName = "test/lock/acquirewaitrelease"; var lockOptions = new LockOptions(keyName) { SessionName = "test_locksession", SessionTTL = TimeSpan.FromSeconds(10) }; var l = client.CreateLock(lockOptions); l.Acquire(CancellationToken.None); Assert.True(l.IsHeld); // Wait for multiple renewal cycles to ensure the lock session stays renewed. Task.Delay(TimeSpan.FromSeconds(60)).Wait(); Assert.True(l.IsHeld); l.Release(); Assert.False(l.IsHeld); l.Destroy(); }
public IDistributedLock CreateLock(LockOptions opts) { throw new NotImplementedException(); }
/// <summary> /// Lock the buffer for a given region and options. You can specify all 0's in your region /// to get the entire texture. /// </summary> /// <param name="region">The region to lock.</param> /// <param name="options">The options to set when locking.</param> /// <returns></returns> public void lockBuf(IntRect region, LockOptions options) { HardwarePixelBuffer_lock(hardwareBuffer, region.Left, region.Top, region.Right, region.Bottom, options); }
private void RunRandomReadWriteOp(Guid[] docIds, LockOptions readOptions, LockOptions writeOptions, int readWriteCount) { var rand = new Random(Thread.CurrentThread.ManagedThreadId); IEntitySession session = null; for(int i = 0; i < readWriteCount; i++) { var randomDocId = docIds[rand.Next(docIds.Length)]; var randomValueName = "N" + rand.Next(5); IDoc iDoc; IDocDetail iDet; int randomOp = -1; try { Thread.Yield(); session = _app.OpenSession(); randomOp = rand.Next(5); switch (randomOp) { case 0: case 1: //insert/update, we give it an edge over deletes, to have 2 upserts for 1 delete session.LogMessage("\r\n----------------- Update/insert value ---------------------"); iDoc = session.GetEntity<IDoc>(randomDocId, writeOptions); Thread.Yield(); iDet = iDoc.Details.FirstOrDefault(iv => iv.Name == randomValueName); if (iDet == null) { iDet = session.NewEntity<IDocDetail>(); iDet.Doc = iDoc; iDet.Name = randomValueName; iDoc.Details.Add(iDet); //to correctly calculate total } iDet.Value = rand.Next(10); iDoc.Total = iDoc.Details.Sum(v => v.Value); Thread.Yield(); session.SaveChanges(); var entSession = (Vita.Entities.Runtime.EntitySession)session; if (entSession.CurrentConnection != null) Debugger.Break(); //check that connection is closed and removed from session break; case 2: //delete if exists session.LogMessage("\r\n----------------- Delete value ---------------------"); //Note: deletes do not throw any errors - if record does not exist (had been just deleted), stored proc do not throw error iDoc = session.GetEntity<IDoc>(randomDocId, writeOptions); Thread.Yield(); //allow others mess up iDet = iDoc.Details.FirstOrDefault(iv => iv.Name == randomValueName); if (iDet != null) { session.DeleteEntity(iDet); iDoc.Details.Remove(iDet); iDoc.Total = iDoc.Details.Sum(v => v.Value); } Thread.Yield(); session.SaveChanges(); // even if there's no changes, it will release lock break; case 3: case 4: //read and check total session.LogMessage("\r\n----------------- Loading doc ---------------------"); iDoc = session.GetEntity<IDoc>(randomDocId, readOptions); Thread.Yield(); //to let other thread mess it up var valuesSum = iDoc.Details.Sum(v => v.Value); if (valuesSum != iDoc.Total) { session.LogMessage("!!!! Sum error: Doc.Total: {0}, Sum(Value): {1}", iDoc.Total, valuesSum); Interlocked.Increment(ref _sumErrorCount); } Thread.Yield(); session.ReleaseLocks(); break; }//switch WriteLog(session); } catch (Exception ex) { //most will be UniqueIndexViolation Debug.WriteLine(ex.ToLogString()); System.Threading.Interlocked.Increment(ref _updateErrorCount); if (session != null) { WriteLog(session); var log = session.Context.LocalLog.GetAllAsText(); Debug.WriteLine(log); var entSession = (Vita.Entities.Runtime.EntitySession)session; if (entSession.CurrentConnection != null) entSession.CurrentConnection.Close(); } } }//for i }
public Task <IDistributedLock> AcquireLock(LockOptions opts, CancellationToken ct = default) { throw new NotImplementedException(); }
public static IQueryable <TEntity> EntitySet <TEntity>(this IEntitySession session, LockOptions options) where TEntity : class { if (options == LockOptions.None) { return(session.EntitySet <TEntity>()); } var entSession = (EntitySession)session; return(entSession.CreateEntitySet <TEntity>(options)); }
/// <summary> /// Tries to acquire an auto setup lock. /// </summary> /// <param name="distributedLock"> /// The distributed lock. /// </param> /// <param name="lockOptions"> /// The auto setup lock options. /// </param> /// <returns> /// The <see cref="ILocker"/> and <c>true</c> if successfully acquired. /// </returns> public static Task <(ILocker locker, bool locked)> TryAcquireAutoSetupLockAsync(this IDistributedLock distributedLock, LockOptions lockOptions) { TimeSpan timeout, expiration; if (distributedLock is ILocalLock) { // If it is a local lock, don't use any timeout and expiration. timeout = expiration = TimeSpan.MaxValue; } else { // If it is a distributed lock, use the configured timeout and expiration. var lockTimeout = lockOptions?.LockTimeout ?? 0; if (lockTimeout <= 0) { lockTimeout = 60_000; } var lockExpiration = lockOptions?.LockExpiration ?? 0; if (lockExpiration <= 0) { lockExpiration = 60_000; } timeout = TimeSpan.FromMilliseconds(lockTimeout); expiration = TimeSpan.FromMilliseconds(lockExpiration); } return(distributedLock.TryAcquireLockAsync("AUTOSETUP_LOCK", timeout, expiration)); }
private static extern void HardwarePixelBuffer_lock(IntPtr hardwarePixelBuffer, int left, int top, int right, int bottom, LockOptions options);
public static bool FindAtomicLockStatusReplicated(RspList results, ref object lockId, ref DateTime lockDate) { bool res = true; LockOptions lockInfo = null; if (results == null) { return(res); } int lockAcquired = 0; int itemNotFound = 0; int rspReceived = results.size(); for (int i = 0; i < results.size(); i++) { Rsp rsp = (Rsp)results.elementAt(i); if (rsp.wasSuspected()) { rspReceived--; continue; } if (!rsp.wasReceived()) { rspReceived--; continue; } lockInfo = (LockOptions)rsp.Value; if (Object.Equals(lockInfo.LockId, lockId)) { lockDate = lockInfo.LockDate; lockAcquired++; } else { if (lockInfo.LockId == null) { //item was not present on the node. lockId = null; lockDate = new DateTime(); itemNotFound++; } else { res = false; lockId = lockInfo.LockId; lockDate = lockInfo.LockDate; break; } } } if (lockAcquired > 0 && (lockAcquired + itemNotFound == rspReceived)) { return(true); } else { return(false); } }
public Task ExecuteLocked(LockOptions opts, CancellationToken ct, Action action) { throw new NotImplementedException(); }
public static bool IsSet(this LockOptions options, LockOptions option) { return((options & option) != 0); }
private IBookOrder GetOpenOrder(IEntitySession session, LockOptions lockOptions, bool create = false) { var currUserId = Context.User.UserId; var openOrder = session.EntitySet<IBookOrder>(lockOptions) .Where(bo => bo.User.Id == currUserId && bo.Status == OrderStatus.Open).FirstOrDefault(); if (openOrder == null && create) { var user = session.GetEntity<IUser>(Context.User.UserId); openOrder = session.NewOrder(user); } return openOrder; }
//For now implemented using dynamically built LINQ query; stored proc support to come later // TODO: save filter Func in EntityInfo and reuse it public static TEntity GetEntity <TEntity>(this IEntitySession session, object primaryKey, LockOptions options) where TEntity : class { if (options == LockOptions.None) { return(session.GetEntity <TEntity>(primaryKey)); //short path, no locks } session.LogMessage("-- Locking entity {0}/{1}", typeof(TEntity).Name, primaryKey); var entInfo = session.Context.App.Model.GetEntityInfo(typeof(TEntity), throwIfNotFound: true); var pkMembers = entInfo.PrimaryKey.KeyMembers; Util.Check(pkMembers.Count == 1, "Cannot lock entity {0}: composite primary keys not supported.", entInfo.Name); var pkMember = entInfo.PrimaryKey.KeyMembers[0].Member; var prmEnt = Expression.Parameter(typeof(TEntity), "e"); var pkRead = Expression.MakeMemberAccess(prmEnt, pkMember.ClrMemberInfo); var eq = Expression.Equal(pkRead, Expression.Constant(primaryKey, pkMember.DataType)); var filter = Expression.Lambda <Func <TEntity, bool> >(eq, prmEnt); var query = session.EntitySet <TEntity>(options).Where(filter); // We use ToList() on entire query instead of First() because we have already filter on PK value, // and we want to avoid adding any paging (skip/take) clauses to the SQL. // We use FirstOrDefult on entire list, and check that we got something; if not, we throw clear message. var ent = query.ToList().FirstOrDefault(); Util.Check(ent != null, "Entity {0} with ID {1} does not exist, cannot set the lock.", entInfo.EntityType.Name, primaryKey); return(ent); /* * //The following is just a sketch * if (checkLastModifiedId != null) { * Util.Check(entInfo.VersioningMember != null, "Entity {0} has no tracking/versioning column (last modified transaction id), cannot check data version.", entInfo.Name); * var lastTransId = EntityHelper.GetProperty<Guid>(ent, entInfo.VersioningMember.MemberName); * session.Context.ThrowIf(doNotUse_checkLastModifiedId.Value != lastTransId, ClientFaultCodes.ConcurrentUpdate, entInfo.VersioningMember.MemberName, "Entity {0} was modified by concurrent process.", entInfo.Name); * } * */ }
private void RunTests(LockOptions readOptions, LockOptions writeOptions, int threadCount = 10, int readWriteCount = 50) { // delete old data and create 5 docs SetupHelper.DeleteAll(_app); var session = _app.OpenSession(); for (int i = 0; i < 5; i++) { var iDoc = session.NewEntity<IDoc>(); iDoc.Name = "D" + i; } session.SaveChanges(); var docIds = session.GetEntities<IDoc>(take: 10).Select(d => d.Id).ToArray(); // clear error counts, _updateErrorCount = 0; _sumErrorCount = 0; // create multiple threads and start reading/writing Task[] tasks = new Task[threadCount]; for(int i = 0; i < threadCount; i++) { tasks[i] = Task.Run(() => RunRandomReadWriteOp(docIds, readOptions, writeOptions, readWriteCount)); } Task.WaitAll(tasks); }