Exemplo n.º 1
0
 /// <summary>
 /// Unlocks the object. Called from Lock.Dispose.
 /// </summary>
 /// <param name="theLock"></param>
 public void Unlock(SyncLock theLock)
 {
     lock (_locks)
     {
         _locks.Remove(theLock.Value);
     }
 }
Exemplo n.º 2
0
        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;
        }
Exemplo n.º 3
0
        /// <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();
            }
        }
Exemplo n.º 4
0
        public void NamePreserved()
        {
            string name = "Hello";

            subject = new SyncLock(name);
            Assert.AreEqual(name, subject.Name);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        public TalkWindowBase()
        {
            _syncObj = new SyncLock();

            Load        += TalkWindowBase_Load;
            FormClosing += TalkWindowBase_FormClosing;
        }
Exemplo n.º 6
0
 /// <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();
 }
Exemplo n.º 7
0
 public DataTypeModule(IDataTypeService service)
 {
     _service = service;
     _locks   = new SyncLock <MemberInfo>();
     _allDataTypeDefinitions = new Lazy <IEnumerable <IDataTypeDefinition> >(() =>
     {
         return(_service.GetAllDataTypeDefinitions());
     });
 }
Exemplo n.º 8
0
        /// <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();
                }
            }
        }
Exemplo n.º 9
0
    /// <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;
        }
    }
Exemplo n.º 10
0
        /// <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);
        }
Exemplo n.º 11
0
 /// <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);
     }
 }
Exemplo n.º 12
0
        /// <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);
            }
        }
Exemplo n.º 13
0
        /// <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;
                }
            }
        }
Exemplo n.º 14
0
        /// <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);
        }
Exemplo n.º 15
0
        /// <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&lt;System.Int32&gt;.</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();
                }
            }
        }
Exemplo n.º 16
0
        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");
        }
Exemplo n.º 17
0
        /// <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;
        }
Exemplo n.º 18
0
    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));
    }
Exemplo n.º 19
0
    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));
    }
Exemplo n.º 20
0
        /// <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();
                }
            }
        }
Exemplo n.º 21
0
 public void Setup()
 {
     subject = new SyncLock("Test", Timeout.Infinite);
 }
Exemplo n.º 22
0
 /// <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;
 }
Exemplo n.º 23
0
 /// <summary>
 /// Unlocks the object. Called from Lock.Dispose.
 /// </summary>
 /// <param name="theLock"></param>
 public void Unlock(SyncLock theLock)
 {
     mLocks.Remove(theLock.Value);
 }
Exemplo n.º 24
0
 protected override T Eval() => SyncLock.ReadValue(() =>
 {
     var result   = base.Eval();
     ValueFactory = null;
     return(result);
 });
Exemplo n.º 25
0
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        public TalkWindowBase()
        {
            _syncObj = new SyncLock();

            Load += TalkWindowBase_Load;
        }
Exemplo n.º 26
0
        /// <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();
                }
            }
        }