/// <summary> /// Unlocks the object. Called from Lock.Dispose. /// </summary> /// <param name="theLock"></param> public void Unlock(SyncLock theLock) { lock (_locks) { _locks.Remove(theLock.Value); } }
public SQLiteTransactionalDataSource(SQLiteDataSource dataSource, IsolationLevel?isolationLevel, bool forwardEvents) : base(new SQLiteDataSourceSettings(dataSource, forwardEvents)) { if (dataSource == null) { throw new ArgumentNullException(nameof(dataSource), $"{nameof(dataSource)} is null."); } Name = dataSource.Name; m_BaseDataSource = dataSource; m_Connection = dataSource.CreateConnection(); m_LockToken = SyncLock.WriterLock(); if (isolationLevel == null) { m_Transaction = m_Connection.BeginTransaction(); } else { m_Transaction = m_Connection.BeginTransaction(isolationLevel.Value); } if (forwardEvents) { ExecutionStarted += (sender, e) => dataSource.OnExecutionStarted(e); ExecutionFinished += (sender, e) => dataSource.OnExecutionFinished(e); ExecutionError += (sender, e) => dataSource.OnExecutionError(e); ExecutionCanceled += (sender, e) => dataSource.OnExecutionCanceled(e); } AuditRules = dataSource.AuditRules; UserValue = dataSource.UserValue; }
/// <summary> /// Generates a line-based debug information string including inline source /// line information. /// </summary> protected internal override void GenerateDebugInfo( StringBuilder builder, Node node, FileLocation location) { base.GenerateDebugInfo(builder, node, location); // Try to load file contents SyncLock.EnterReadLock(); try { if (fileMapping.TryGetValue(location.FileName, out var lines)) { // Append associated source lines for ( int i = location.StartLine; i <= location.EndLine; ++i) { builder.Append("\t// "); builder.AppendLine(lines[i - 1].Trim()); } } else { // No debug information could be found builder.AppendLine("\t// <No Source Line>"); } } finally { SyncLock.ExitReadLock(); } }
public void NamePreserved() { string name = "Hello"; subject = new SyncLock(name); Assert.AreEqual(name, subject.Name); }
/// <summary> /// Initializes a new instance of the class. /// </summary> public TalkWindowBase() { _syncObj = new SyncLock(); Load += TalkWindowBase_Load; FormClosing += TalkWindowBase_FormClosing; }
/// <summary> /// Initializes an new instance of the DialogCommon class. Create this /// class in the constructor of the form. /// </summary> /// <param name="form">The dialog form </param> public DialogCommon(Form form) { _form = form; _form.ShowInTaskbar = false; _panelName = String.Empty; _dialogPanel = (IDialogPanel)_form; _syncLock = new SyncLock(); }
public DataTypeModule(IDataTypeService service) { _service = service; _locks = new SyncLock <MemberInfo>(); _allDataTypeDefinitions = new Lazy <IEnumerable <IDataTypeDefinition> >(() => { return(_service.GetAllDataTypeDefinitions()); }); }
/// <summary> /// execute as an asynchronous operation. /// </summary> /// <param name="executionToken">The execution token.</param> /// <param name="implementation">The implementation.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="state">The state.</param> /// <returns>Task.</returns> protected override async Task <int?> ExecuteAsync(OperationExecutionToken <SQLiteConnection, SQLiteTransaction> executionToken, OperationImplementationAsync <SQLiteConnection, SQLiteTransaction> implementation, CancellationToken cancellationToken, object?state) { if (executionToken == null) { throw new ArgumentNullException(nameof(executionToken), $"{nameof(executionToken)} is null."); } if (implementation == null) { throw new ArgumentNullException(nameof(implementation), $"{nameof(implementation)} is null."); } var mode = DisableLocks ? LockType.None : (executionToken as SQLiteOperationExecutionToken)?.LockType ?? LockType.Write; var startTime = DateTimeOffset.Now; OnExecutionStarted(executionToken, startTime, state); IDisposable?lockToken = null; try { switch (mode) { case LockType.Read: lockToken = await SyncLock.ReaderLockAsync().ConfigureAwait(false); break; case LockType.Write: lockToken = await SyncLock.WriterLockAsync().ConfigureAwait(false); break; } var rows = await implementation(m_Connection, m_Transaction, cancellationToken).ConfigureAwait(false); OnExecutionFinished(executionToken, startTime, DateTimeOffset.Now, rows, state); return(rows); } catch (Exception ex) { if (cancellationToken.IsCancellationRequested) //convert SQLiteException into a OperationCanceledException { var ex2 = new OperationCanceledException("Operation was canceled.", ex, cancellationToken); OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex2, state); throw ex2; } else { OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state); throw; } } finally { if (lockToken != null) { lockToken.Dispose(); } } }
/// <summary> /// Releases the lock. Subsequent calls to this method do nothing. /// </summary> public void Dispose() { switch (parent) { case null: return; default: parent.Unlock(); parent = null; break; } }
/// <summary> /// Initializes a new instance of the class. /// </summary> public VolumeSettingsScanner() { InitializeComponent(); _syncObj = new SyncLock(); Load += VolumeSettingsScanner_Load; FormClosing += VolumeSettingsScanner_FormClosing; PanelClass = "VolumeSettingsScanner"; _dispatcher = new Dispatcher(this); }
/// <summary> /// Returns an object that can be used in a lock statement. Ex: lock(MySync.Lock(MyValue)) { ... } /// </summary> /// <param name="value"></param> /// <returns></returns> public SyncLock Lock(T value) { lock (mLock) { SyncLock theLock; if (mLocks.TryGetValue(value, out theLock)) { return(theLock); } theLock = new SyncLock(value, this); mLocks.Add(value, theLock); return(theLock); } }
/// <summary> /// Returns an object that can be used in a lock statement. Ex: lock(MySync.Lock(MyValue)) { ... } /// </summary> /// <param name="value"></param> /// <returns></returns> public SyncLock Lock(T value) { lock (_mLock) { if (_locks.TryGetValue(value, out SyncLock theLock)) { return(theLock); } theLock = new SyncLock(value, this); _locks.Add(value, theLock); return(theLock); } }
/// <summary> /// Initializes a new instance of the class. /// </summary> public ACATMuteForm() { InitializeComponent(); _syncObj = new SyncLock(); ShowInTaskbar = false; if (!initialize()) { Log.Debug("Initialization error!"); } TopMost = true; RoundedCornerControl.CreateRoundedControl(Title); Windows.ShowWindowBorder(this, Common.AppPreferences.ScannerShowBorder); Windows.SetWindowPosition(this, Windows.WindowPosition.CenterScreen); _windowOverlapWatchdog = new WindowOverlapWatchdog(this); updateDateTime(); // Title isn't used on this form, but we keep it hidden instead of removing it // so we don't have to modify the IScreenInterface GetTitle() method Title.Hide(); // timer used for displaying the time timer.Start(); FormBorderStyle = FormBorderStyle.None; WindowState = FormWindowState.Maximized; Load += MuteForm_Load; FormClosing += MuteForm_FormClosing; var actuator = ActuatorManager.Instance.GetActuator(typeof(KeyboardActuator)); if (actuator != null) { _keyboardActuator = actuator as KeyboardActuator; if (_keyboardActuator != null) { _keyboardActuator.EvtKeyDown += _keyboardActuator_EvtKeyDown; _keyboardActuator.EvtKeyUp += _keyboardActuator_EvtKeyUp; } } }
/// <summary> /// Instantiates a new instance of the class /// </summary> /// <param name="iScannerPanel">The scanner Form object</param> public ScannerCommon(IScannerPanel iScannerPanel) { ScannerForm = iScannerPanel.Form; StartupArg = null; _scannerPanel = iScannerPanel; ScannerForm.ShowInTaskbar = false; PositionSizeController = new ScannerPositionSizeController(this); TextController = new TextController(); KeepTalkWindowActive = false; _syncLock = new SyncLock(); var scannerStatusBar = (ScannerForm is ISupportsStatusBar) ? ((ISupportsStatusBar)ScannerForm).ScannerStatusBar : null; StatusBarController = new StatusBarController(scannerStatusBar); }
/// <summary> /// Executes the specified operation. /// </summary> /// <param name="executionToken">The execution token.</param> /// <param name="implementation">The implementation.</param> /// <param name="state">The state.</param> /// <returns>System.Nullable<System.Int32>.</returns> protected override int?Execute(OperationExecutionToken <SQLiteConnection, SQLiteTransaction> executionToken, OperationImplementation <SQLiteConnection, SQLiteTransaction> implementation, object?state) { if (executionToken == null) { throw new ArgumentNullException(nameof(executionToken), $"{nameof(executionToken)} is null."); } if (implementation == null) { throw new ArgumentNullException(nameof(implementation), $"{nameof(implementation)} is null."); } var mode = DisableLocks ? LockType.None : (executionToken as SQLiteOperationExecutionToken)?.LockType ?? LockType.Write; var startTime = DateTimeOffset.Now; OnExecutionStarted(executionToken, startTime, state); IDisposable?lockToken = null; try { switch (mode) { case LockType.Read: lockToken = SyncLock.ReaderLock(); break; case LockType.Write: lockToken = SyncLock.WriterLock(); break; } var rows = implementation(m_Connection, m_Transaction); OnExecutionFinished(executionToken, startTime, DateTimeOffset.Now, rows, state); return(rows); } catch (Exception ex) { OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state); throw; } finally { if (lockToken != null) { lockToken.Dispose(); } } }
public void AlreadyOwned() { DateTime start, end; object monitor = new object(); lock (monitor) { start = DateTime.UtcNow; for (int i = 0; i < Iterations; i++) { lock (monitor) { } } end = DateTime.UtcNow; } TimeSpan nativeTime = end - start; SyncLock syncLock = new SyncLock(Timeout.Infinite); using (syncLock.Lock()) { start = DateTime.UtcNow; for (int i = 0; i < Iterations; i++) { using (syncLock.Lock()) { } } end = DateTime.UtcNow; } TimeSpan syncLockTime = end - start; double factor = syncLockTime.TotalMilliseconds / nativeTime.TotalMilliseconds; Console.WriteLine("Performance of SyncLock (lock already owned):"); Console.WriteLine("Native: {0}", nativeTime); Console.WriteLine("SyncLock: {0}", syncLockTime); Console.WriteLine("Performance penalty factor: {0:0.00}", factor); Console.WriteLine(); Assert.IsTrue(factor < 10, "SyncLock must not be ridiculously slow"); }
/// <summary> /// Initializes the player /// </summary> /// <param name="rootWidget">root widget for the scanner</param> /// <param name="interpreter">the interpreter object</param> /// <param name="variables">variables and their values</param> public AnimationPlayer(Widget rootWidget, Interpret interpreter, Variables variables) { Log.Debug("CTOR(" + rootWidget.Name + ")"); if (rootWidget.UIControl is IPanel) { _syncObj = (rootWidget.UIControl as IPanel).SyncObj; } _transitionSync = _syncObj; _interpreter = interpreter; _timer = new System.Timers.Timer(); _timer.Elapsed += timer_Elapsed; _highlightedWidget = null; _currentAnimation = null; _rootWidget = rootWidget; _playerState = PlayerState.Stopped; _variables = variables; _inTimer = false; }
private partial SQLiteTransactionalDataSource OnBeginTransaction(IsolationLevel?isolationLevel, bool forwardEvents) { IDisposable?lockToken = null; if (!DisableLocks) { lockToken = SyncLock.WriterLock(); } var connection = CreateConnection(); SQLiteTransaction transaction; if (isolationLevel == null) { transaction = connection.BeginTransaction(); } else { transaction = connection.BeginTransaction(isolationLevel.Value); } return(new SQLiteTransactionalDataSource(this, forwardEvents, connection, transaction, lockToken)); }
private partial async Task <SQLiteTransactionalDataSource> OnBeginTransactionAsync(IsolationLevel?isolationLevel, bool forwardEvents, CancellationToken cancellationToken) { IDisposable?lockToken = null; if (!DisableLocks) { lockToken = await SyncLock.WriterLockAsync(); } var connection = await CreateConnectionAsync(cancellationToken).ConfigureAwait(false); SQLiteTransaction transaction; if (isolationLevel == null) { transaction = connection.BeginTransaction(); } else { transaction = connection.BeginTransaction(isolationLevel.Value); } return(new SQLiteTransactionalDataSource(this, forwardEvents, connection, transaction, lockToken)); }
/// <summary> /// Executes the operation asynchronously. /// </summary> /// <param name="executionToken">The execution token.</param> /// <param name="implementation">The implementation that handles processing the result of the command.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="state">User supplied state.</param> /// <returns>Task.</returns> /// <exception cref="NotImplementedException"></exception> protected override async Task <int?> ExecuteAsync(CommandExecutionToken <SQLiteCommand, SQLiteParameter> executionToken, CommandImplementationAsync <SQLiteCommand> implementation, CancellationToken cancellationToken, object?state) { if (executionToken == null) { throw new ArgumentNullException(nameof(executionToken), $"{nameof(executionToken)} is null."); } if (implementation == null) { throw new ArgumentNullException(nameof(implementation), $"{nameof(implementation)} is null."); } var mode = DisableLocks ? LockType.None : (executionToken as SQLiteCommandExecutionToken)?.LockType ?? LockType.Write; var startTime = DateTimeOffset.Now; OnExecutionStarted(executionToken, startTime, state); IDisposable?lockToken = null; try { switch (mode) { case LockType.Read: lockToken = await SyncLock.ReaderLockAsync().ConfigureAwait(false); break; case LockType.Write: lockToken = await SyncLock.WriterLockAsync().ConfigureAwait(false); break; } using (var cmd = new SQLiteCommand()) { cmd.Connection = m_Connection; if (m_Transaction != null) { cmd.Transaction = m_Transaction; } if (DefaultCommandTimeout.HasValue) { cmd.CommandTimeout = (int)DefaultCommandTimeout.Value.TotalSeconds; } cmd.CommandText = executionToken.CommandText; cmd.CommandType = executionToken.CommandType; foreach (var param in executionToken.Parameters) { cmd.Parameters.Add(param); } executionToken.ApplyCommandOverrides(cmd); var rows = await implementation(cmd).ConfigureAwait(false); executionToken.RaiseCommandExecuted(cmd, rows); OnExecutionFinished(executionToken, startTime, DateTimeOffset.Now, rows, state); return(rows); } } catch (Exception ex) { if (cancellationToken.IsCancellationRequested) //convert SQLiteException into a OperationCanceledException { var ex2 = new OperationCanceledException("Operation was canceled.", ex, cancellationToken); OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex2, state); throw ex2; } else { OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state); throw; } } finally { if (lockToken != null) { lockToken.Dispose(); } } }
public void Setup() { subject = new SyncLock("Test", Timeout.Infinite); }
/// <summary> /// Constructs a new lock token for the specified lock. /// </summary> /// <param name="parent">The internal monitor used for locking.</param> internal LockToken(SyncLock parent) { this.parent = parent; }
/// <summary> /// Unlocks the object. Called from Lock.Dispose. /// </summary> /// <param name="theLock"></param> public void Unlock(SyncLock theLock) { mLocks.Remove(theLock.Value); }
protected override T Eval() => SyncLock.ReadValue(() => { var result = base.Eval(); ValueFactory = null; return(result); });
/// <summary> /// Initializes a new instance of the class. /// </summary> public TalkWindowBase() { _syncObj = new SyncLock(); Load += TalkWindowBase_Load; }
/// <summary> /// Executes the specified operation. /// </summary> /// <param name="executionToken">The execution token.</param> /// <param name="implementation">The implementation that handles processing the result of the command.</param> /// <param name="state">User supplied state.</param> /// <exception cref="ArgumentNullException"> /// executionToken;executionToken is null. /// or /// implementation;implementation is null. /// </exception> protected override int?Execute(CommandExecutionToken <SQLiteCommand, SQLiteParameter> executionToken, CommandImplementation <SQLiteCommand> implementation, object?state) { if (executionToken == null) { throw new ArgumentNullException(nameof(executionToken), $"{nameof(executionToken)} is null."); } if (implementation == null) { throw new ArgumentNullException(nameof(implementation), $"{nameof(implementation)} is null."); } var mode = DisableLocks ? LockType.None : (executionToken as SQLiteCommandExecutionToken)?.LockType ?? LockType.Write; var startTime = DateTimeOffset.Now; OnExecutionStarted(executionToken, startTime, state); IDisposable?lockToken = null; try { switch (mode) { case LockType.Read: lockToken = SyncLock.ReaderLock(); break; case LockType.Write: lockToken = SyncLock.WriterLock(); break; } using (var cmd = new SQLiteCommand()) { cmd.Connection = m_Connection; if (m_Transaction != null) { cmd.Transaction = m_Transaction; } if (DefaultCommandTimeout.HasValue) { cmd.CommandTimeout = (int)DefaultCommandTimeout.Value.TotalSeconds; } cmd.CommandText = executionToken.CommandText; cmd.CommandType = executionToken.CommandType; foreach (var param in executionToken.Parameters) { cmd.Parameters.Add(param); } executionToken.ApplyCommandOverrides(cmd); var rows = implementation(cmd); executionToken.RaiseCommandExecuted(cmd, rows); OnExecutionFinished(executionToken, startTime, DateTimeOffset.Now, rows, state); return(rows); } } catch (Exception ex) { OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state); throw; } finally { if (lockToken != null) { lockToken.Dispose(); } } }