Example #1
0
        public MainWindow()
        {
            InitializeComponent();
            titleLead = $"Slapp - {splatTagController.MatchPlayer(null).Length} Players and {splatTagController.MatchTeam(null).Length} Teams loaded! - ";
            Title     = titleLead;

            // Initialise the delay timer if we have a UI context, otherwise don't use the timer.
            context = SynchronizationContext.Current;
            if (context != null)
            {
                smoothSearchDelayTimer = new Timer(TimerExpired);
            }

            // If we've loaded from a snapshot, then hide the setup button(s).
            if (sourcesImporter == null)
            {
                otherFunctionsGrid.Visibility = Visibility.Collapsed;
            }

            // Re-save if needed
            // SplatTagControllerFactory.SaveDatabase(splatTagController);

            // Now we've initialised, hook up the check changed.
            ignoreCaseCheckbox.Checked   += CheckedChanged;
            ignoreCaseCheckbox.Unchecked += CheckedChanged;
            nearMatchCheckbox.Checked    += CheckedChanged;
            nearMatchCheckbox.Unchecked  += CheckedChanged;
            regexCheckbox.Checked        += CheckedChanged;
            regexCheckbox.Unchecked      += CheckedChanged;

            // Focus the input text box so we can start typing as soon as the program starts.
            searchInput.Focus();
        }
        public void OnCompleted(Action <object?> continuation, object?state, ValueTaskSourceOnCompletedFlags flags, out CompletionData completionData, out bool doubleCompletion)
        {
            completionData   = default;
            doubleCompletion = !ReferenceEquals(_completion, null);

            if (IsCompleted || doubleCompletion)
            {
                completionData = new CompletionData(continuation, state, _executionContext, _synchronizationContext);
                return;
            }

            _completion      = continuation;
            _completionState = state;

            // Capture the SynchronizationContext if there's any and we're allowing capture (from pipe options)
            if ((_awaitableState & AwaitableState.UseSynchronizationContext) != 0 &&
                (flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0)
            {
                SynchronizationContext?sc = SynchronizationContext.Current;
                if (sc != null && sc.GetType() != typeof(SynchronizationContext))
                {
                    _synchronizationContext = sc;
                }
            }

            // Capture the execution context
            if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0)
            {
                _executionContext = ExecutionContext.Capture();
            }
        }
            static async void OnCompletedSlow(ValueTask source, Action <object?> continuation, object?state, ValueTaskSourceOnCompletedFlags flags)
            {
                ExecutionContext?      execContext = null;
                SynchronizationContext?syncContext = null;

                if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) == ValueTaskSourceOnCompletedFlags.FlowExecutionContext)
                {
                    execContext = ExecutionContext.Capture();
                }
                if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) == ValueTaskSourceOnCompletedFlags.UseSchedulingContext)
                {
                    syncContext = SynchronizationContext.Current;
                }

                try
                {
                    await source.ConfigureAwait(false);
                }
                catch { }

                if (execContext != null)
                {
                    ExecutionContext.Run(execContext, execContextCallback, Tuple.Create(continuation, state, syncContext));
                }
                else if (syncContext != null)
                {
                    syncContext.Post(syncContextCallback, Tuple.Create(continuation, state, syncContext));
                }
                else
                {
                    continuation(state);
                }
            }
    public void ConfigureAwaitRunInlineOfT_NoExtraThreadSwitching(NamedSyncContext invokeOn, NamedSyncContext completeOn)
    {
        // Set up various SynchronizationContexts that we may invoke or complete the async method with.
        SynchronizationContext?aSyncContext        = SingleThreadedTestSynchronizationContext.New();
        SynchronizationContext?bSyncContext        = SingleThreadedTestSynchronizationContext.New();
        SynchronizationContext?invokeOnSyncContext = invokeOn == NamedSyncContext.None ? null
            : invokeOn == NamedSyncContext.A ? aSyncContext
            : invokeOn == NamedSyncContext.B ? bSyncContext
            : throw new ArgumentOutOfRangeException(nameof(invokeOn));
        SynchronizationContext?completeOnSyncContext = completeOn == NamedSyncContext.None ? null
            : completeOn == NamedSyncContext.A ? aSyncContext
            : completeOn == NamedSyncContext.B ? bSyncContext
            : throw new ArgumentOutOfRangeException(nameof(completeOn));

        // Set up a single-threaded SynchronizationContext that we'll invoke the async method within.
        SynchronizationContext.SetSynchronizationContext(invokeOnSyncContext);

        var        unblockAsyncMethod = new TaskCompletionSource <bool>();
        Task <int>?asyncTask          = AwaitThenGetThreadAsync(unblockAsyncMethod.Task);

        SynchronizationContext.SetSynchronizationContext(completeOnSyncContext);
        unblockAsyncMethod.SetResult(true);

        // Confirm that setting the intermediate task allowed the async method to complete immediately, using our thread to do it.
        Assert.True(asyncTask.IsCompleted);
        Assert.Equal(Environment.CurrentManagedThreadId, asyncTask.Result);

        async Task <int> AwaitThenGetThreadAsync(Task <bool> antecedent)
        {
            bool result = await antecedent.ConfigureAwaitRunInline();

            Assert.True(result);
            return(Environment.CurrentManagedThreadId);
        }
    }
    public void SynchronizationContextCaptured()
    {
        SynchronizationContext?syncContext = SingleThreadedTestSynchronizationContext.New();

        SynchronizationContext.SetSynchronizationContext(syncContext);
        TaskCompletionSource <object?> callbackResult = new TaskCompletionSource <object?>();

        SingleThreadedTestSynchronizationContext.IFrame?frame = SingleThreadedTestSynchronizationContext.NewFrame();
        var callback = new Action <GenericParameterHelper>(
            p =>
        {
            try
            {
                Assert.NotNull(SynchronizationContext.Current);
                callbackResult.SetResult(null);
            }
            catch (Exception e)
            {
                callbackResult.SetException(e);
            }

            frame.Continue = false;
        });
        var progress = new ProgressWithCompletion <GenericParameterHelper>(callback);
        IProgress <GenericParameterHelper> reporter = progress;

        Task.Run(delegate
        {
            reporter.Report(new GenericParameterHelper(1));
        });

        SingleThreadedTestSynchronizationContext.PushFrame(syncContext, frame);
        callbackResult.Task.GetAwaiter().GetResult();
    }
Example #6
0
    public void WithCancellationNoDeadlockFromSyncContext_Completed()
    {
        SynchronizationContext?dispatcher = SingleThreadedTestSynchronizationContext.New();

        SynchronizationContext.SetSynchronizationContext(dispatcher);
        WithCancellationSyncBlock(simulateCancellation: false);
    }
Example #7
0
    public void WithCancellationNoncancelableNoDeadlockFromSyncContext()
    {
        SynchronizationContext?dispatcher = SingleThreadedTestSynchronizationContext.New();

        SynchronizationContext.SetSynchronizationContext(dispatcher);
        WithCancellationSyncBlockOnNoncancelableToken();
    }
            public void OnCompleted(Action <object?> continuation, object?state, short token, ValueTaskSourceOnCompletedFlags flags)
            {
                var c = Interlocked.CompareExchange(ref this.continuation, continuation, ContinuationSentinel.AvailableContinuation);

                if (c == ContinuationSentinel.CompletedContinuation)
                {
                    continuation(state);
                    return;
                }

                if (c != ContinuationSentinel.AvailableContinuation)
                {
                    throw new InvalidOperationException("does not allow multiple await.");
                }

                if (state == null)
                {
                    throw new InvalidOperationException("invalid state.");
                }

                if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) == ValueTaskSourceOnCompletedFlags.FlowExecutionContext)
                {
                    execContext = ExecutionContext.Capture();
                }
                if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) == ValueTaskSourceOnCompletedFlags.UseSchedulingContext)
                {
                    syncContext = SynchronizationContext.Current;
                }
                this.state = state;

                if (GetStatus(token) != ValueTaskSourceStatus.Pending)
                {
                    TryInvokeContinuation();
                }
            }
        /// <summary>
        /// Posts the given action to the given SynchronizationContext also if it is null.
        /// If it is null, then a new task will be started.
        /// </summary>
        /// <param name="syncContext">The context to send the action to.</param>
        /// <param name="actionToPost">The action to be executed on the target thread.</param>
        /// <param name="actionIfNull">What should we do if weg get no SyncContext?</param>
        public static void PostAlsoIfNull(
            this SynchronizationContext?syncContext,
            Action actionToPost,
            ActionIfSyncContextIsNull actionIfNull = ActionIfSyncContextIsNull.InvokeUsingNewTask)
        {
            if (syncContext != null)
            {
                syncContext.Post((_) => actionToPost(), null);
            }
            else
            {
                switch (actionIfNull)
                {
                case ActionIfSyncContextIsNull.InvokeSynchronous:
                    actionToPost();
                    break;

                case ActionIfSyncContextIsNull.InvokeUsingNewTask:
                    Task.Factory.StartNew(actionToPost);
                    break;

                case ActionIfSyncContextIsNull.DontInvoke:
                    break;

                default:
                    throw new ArgumentException("actionIfNull", "Action " + actionIfNull + " unknown!");
                }
            }
        }
Example #10
0
    /// <summary>
    /// Runs an asynchronous task synchronously, using just the current thread to execute continuations.
    /// </summary>
    internal static void Run(Func <Task> func)
    {
        if (func is null)
        {
            throw new ArgumentNullException(nameof(func));
        }

        SynchronizationContext?prevCtx = SynchronizationContext.Current;

        try
        {
            SynchronizationContext?syncCtx = SingleThreadedTestSynchronizationContext.New();
            SynchronizationContext.SetSynchronizationContext(syncCtx);

            Task?t = func();
            if (t is null)
            {
                throw new InvalidOperationException();
            }

            SingleThreadedTestSynchronizationContext.IFrame?frame = SingleThreadedTestSynchronizationContext.NewFrame();
            t.ContinueWith(_ => { frame.Continue = false; }, TaskScheduler.Default);
            SingleThreadedTestSynchronizationContext.PushFrame(syncCtx, frame);

            t.GetAwaiter().GetResult();
        }
        finally
        {
            SynchronizationContext.SetSynchronizationContext(prevCtx);
        }
    }
 public CompletionData(Action <object?> completion, object?completionState, ExecutionContext?executionContext, SynchronizationContext?synchronizationContext)
 {
     Completion             = completion;
     CompletionState        = completionState;
     ExecutionContext       = executionContext;
     SynchronizationContext = synchronizationContext;
 }
Example #12
0
        public static void Start <TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
        {
            if (stateMachine == null) // TStateMachines are generally non-nullable value types, so this check will be elided
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stateMachine);
            }

            Thread currentThread = Thread.CurrentThread;

            // Store current ExecutionContext and SynchronizationContext as "previousXxx".
            // This allows us to restore them and undo any Context changes made in stateMachine.MoveNext
            // so that they won't "leak" out of the first await.
            ExecutionContext?      previousExecutionCtx = currentThread._executionContext;
            SynchronizationContext?previousSyncCtx      = currentThread._synchronizationContext;

            try
            {
                stateMachine.MoveNext();
            }
            finally
            {
                // The common case is that these have not changed, so avoid the cost of a write barrier if not needed.
                if (previousSyncCtx != currentThread._synchronizationContext)
                {
                    // Restore changed SynchronizationContext back to previous
                    currentThread._synchronizationContext = previousSyncCtx;
                }

                ExecutionContext?currentExecutionCtx = currentThread._executionContext;
                if (previousExecutionCtx != currentExecutionCtx)
                {
                    ExecutionContext.RestoreChangedContextToThread(currentThread, previousExecutionCtx, currentExecutionCtx);
                }
            }
        }
Example #13
0
        private AsyncCmdletContext(
            Cmdlet cmdlet)
        {
            if (!_contexts.TryAdd(cmdlet, this))
            {
                throw new InvalidOperationException();
            }

            this._originalSynchronizationContext = SynchronizationContext.Current;

            this._cmdlet = cmdlet;

            this._mainThreadId = Thread.CurrentThread.ManagedThreadId;

            this._queue = new BlockingCollection <IAction>();

            this._cts = new CancellationTokenSource();

            this._diagnosticSource = new SwitchingDiagnosticSource(
                DiagnosticConstants.SourceName,
                DiagnosticConstants.TraceSwitchName);

            var syncCtx = new PowerShellSynchronizationContext(this);

            SynchronizationContext.SetSynchronizationContext(syncCtx);

            this._diagnosticSource.Write(
                DiagnosticConstants.Construct,
                Unit.Instance);
        }
    public void CreateCopy()
    {
        SynchronizationContext?copy = this.nonSticky.CreateCopy();

        Assert.NotSame(this.nonSticky, copy);
        ConfirmNonConcurrentPost(this.nonSticky, copy);
    }
Example #15
0
        /// <summary>Creates an IAsyncInfo from the specified delegate. The delegate will be called to construct a task that will
        /// represent the future encapsulated by this IAsyncInfo.</summary>
        /// <param name="taskProvider">The task generator to use for creating the task.</param>
        internal TaskToAsyncInfoAdapter(Delegate taskProvider)
        {
            Debug.Assert(taskProvider != null);
            Debug.Assert((null != (taskProvider as Func <Task>)) ||
                         (null != (taskProvider as Func <CancellationToken, Task>)) ||
                         (null != (taskProvider as Func <IProgress <TProgressInfo>, Task>)) ||
                         (null != (taskProvider as Func <CancellationToken, IProgress <TProgressInfo>, Task>)));

            // The IAsyncInfo is reasonably expected to be created/started by the same code that wires up the Completed and Progress handlers.
            // Record the current SynchronizationContext so that we can invoke completion and progress callbacks in it later.
            _startingContext = GetStartingContext();

            // Construct task from the specified provider:
            Task task = InvokeTaskProvider(taskProvider);

            if (task == null)
            {
                throw new NullReferenceException(SR.NullReference_TaskProviderReturnedNull);
            }

            if (task.Status == TaskStatus.Created)
            {
                throw new InvalidOperationException(SR.InvalidOperation_TaskProviderReturnedUnstartedTask);
            }

            _dataContainer = task;
            _state         = (STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_STARTED);

            // Set the completion routine and let the task running:
            task.ContinueWith(
                (_, this_) => ((TaskToAsyncInfoAdapter <TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_ !).TaskCompleted(),
                this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
        }
        public TemporarySynchronizationContext(SynchronizationContext context)
        {
            Contract.Requires(context != null);

            this.originalContext  = SynchronizationContext.Current;
            this.temporaryContext = context;
            SynchronizationContext.SetSynchronizationContext(context);
        }
Example #17
0
 /// <summary>
 /// Create and start timer to wait for a minimum amount of time
 /// </summary>
 private void StartMinimumTimer()
 {
     timerSynchronizatinContext     = SynchronizationContext.Current;
     minimumIntervalTimer           = new System.Timers.Timer(minimumWaitTimeInSeconds * 1000);
     minimumIntervalTimer.AutoReset = false;
     minimumIntervalTimer.Elapsed  += OnTimerElapsed;
     minimumIntervalTimer.Start();
 }
Example #18
0
    public static bool IsSingleThreadedSyncContext([NotNullWhen(true)] SynchronizationContext?context)
    {
#if UseWpfContext
        return(context is DispatcherSynchronizationContext);
#else
        return(context is SingleThreadedSynchronizationContext);
#endif
    }
    public StaFactTest()
    {
        _ctorSyncContext = SynchronizationContext.Current;

        _ctorThreadId = Environment.CurrentManagedThreadId;

        Assert.NotNull(_ctorSyncContext);
    }
Example #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpecializedSyncContext"/> struct.
 /// </summary>
 private SpecializedSyncContext(SynchronizationContext?syncContext, bool checkForChangesOnRevert)
 {
     this.initialized             = true;
     this.prior                   = SynchronizationContext.Current;
     this.appliedContext          = syncContext;
     this.checkForChangesOnRevert = checkForChangesOnRevert;
     SynchronizationContext.SetSynchronizationContext(syncContext);
 }
        /// <summary>
        /// Stores the continuation for later execution when <see cref="Resume"/> is invoked.
        /// </summary>
        /// <param name="continuation">The delegate to execute later.</param>
        public void OnCompleted(Action continuation)
        {
            Requires.NotNull(continuation, nameof(continuation));
            Assumes.Null(this.continuation); // Only one continuation is supported.

            this.capturedSynchronizationContext = SynchronizationContext.Current;
            this.continuation = continuation;
        }
Example #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FirLib.Core.Patterns.Messaging.FirLibMessenger"/> class.
        /// </summary>
        public FirLibMessenger()
        {
            _globalMessengerName  = string.Empty;
            _hostSyncContext      = null;
            _publishCheckBehavior = FirLibMessengerThreadingBehavior.Ignore;

            _messageSubscriptions     = new Dictionary <Type, List <MessageSubscription> >();
            _messageSubscriptionsLock = new object();
        }
Example #23
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="ViewModelBase" /> class.
 /// </summary>
 /// <param name="busyScope">The busy scope.</param>
 /// <param name="synchronizationContext">The specific synchronization context to use.</param>
 protected ViewModelBase(
     BusyScope?busyScope,
     SynchronizationContext?synchronizationContext = null)
     : base(synchronizationContext)
 {
     entityErrors   = new Lazy <ConcurrentDictionary <string, List <string> > >();
     validatorLock  = new object();
     this.busyScope = busyScope;
 }
Example #24
0
        public static TService SetSyncContext <TService>(this TService rpcService, SynchronizationContext?syncContext) where TService : class, IRpcProxy
        {
            if (rpcService is RpcProxyBase proxyBase)
            {
                return(proxyBase.Channel.GetServiceInstance <TService>(proxyBase.ObjectId, proxyBase.ImplementedServices, syncContext));
            }

            throw new ArgumentException("Can only set synchronization context on services retrieved using IRpcConnection.");
        }
Example #25
0
        public RealmLive(T data)
        {
            this.data = data;

            fetchedContext  = SynchronizationContext.Current;
            fetchedThreadId = Thread.CurrentThread.ManagedThreadId;

            ID = data.ID;
        }
            internal Disposable(SynchronizationContext?synchronizationContext)
            {
                if (synchronizationContext != null)
                {
                    SynchronizationContext.SetSynchronizationContext(null);
                }

                _synchronizationContext = synchronizationContext;
            }
Example #27
0
 internal AssemblyList(AssemblyListManager manager, string listName)
 {
     this.manager  = manager ?? throw new ArgumentNullException(nameof(manager));
     this.listName = listName;
     this.ApplyWinRTProjections = manager.ApplyWinRTProjections;
     this.UseDebugSymbols       = manager.UseDebugSymbols;
     ownerThread                   = Thread.CurrentThread;
     synchronizationContext        = SynchronizationContext.Current;
     assemblies.CollectionChanged += Assemblies_CollectionChanged;
 }
Example #28
0
 public void Disable()
 {
     timer?.Stop();
     if (timer is not null)
     {
         timer.Elapsed -= OnTimerElapsed;
     }
     timer = null;
     synchronizationContext = null;
 }
Example #29
0
        public ProgressMonitor(SynchronizationContext?context, CancellationTokenSource?cancellationTokenSource)
        {
            this.cancellationTokenSource = cancellationTokenSource;
            this.context           = context;
            logWriter              = new LogTextWriter(context);
            logWriter.TextWritten += DoWriteLog;

            errorLogWriter              = new LogTextWriter(context);
            errorLogWriter.TextWritten += DoWriteErrorLog;
        }
Example #30
0
        public PlatformTicker()
        {
            if (SynchronizationContext.Current == null)
            {
                TizenSynchronizationContext.Initialize();
            }

            _context = SynchronizationContext.Current;
            _timer   = new Timer((object?o) => HandleElapsed(o), this, Timeout.Infinite, Timeout.Infinite);
        }