Exemple #1
0
        /// <summary>
        /// Sends the specified function to the <paramref name="synchronizationContext" /> and returns its result.
        /// </summary>
        /// <typeparam name="TState">The type of the <paramref name="state"/> parameter.</typeparam>
        /// <typeparam name="TResult">The type of the result.</typeparam>
        /// <param name="synchronizationContext">The synchronization context.</param>
        /// <param name="func">The function.</param>
        /// <param name="state">The state to pass along.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">
        /// synchronizationContext
        /// or
        /// func
        /// </exception>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static TResult Send <TState, TResult>(this SynchronizationContext synchronizationContext, Func <TState, TResult> func, TState state)
        {
            if (synchronizationContext == null)
            {
                throw new ArgumentNullException(nameof(synchronizationContext));
            }
            if (func == null)
            {
                throw new ArgumentNullException(nameof(func));
            }

            var result = default(TResult);

            synchronizationContext.OperationStarted();
            synchronizationContext.Send(o =>
            {
                try
                {
                    result = func((TState)o);
                }
                finally
                {
                    synchronizationContext.OperationCompleted();
                }
            }, state);

            return(result);
        }
 /// <summary>
 ///     Constructor. Protected to avoid unwitting usage - AsyncOperation objects
 ///     are typically created by AsyncOperationManager calling CreateOperation.
 /// </summary>
 private AsyncOperation(object userSuppliedState, SynchronizationContext syncContext)
 {
     _userSuppliedState = userSuppliedState;
     _syncContext       = syncContext;
     _alreadyCompleted  = false;
     _syncContext.OperationStarted();
 }
Exemple #3
0
        /// <summary>
        ///     Initializes the <see cref="AsyncVoidMethodBuilder" />.
        /// </summary>
        /// <param name="synchronizationContext">The synchronizationContext associated with this operation. This may be null.</param>
        private AsyncVoidMethodBuilder(SynchronizationContext synchronizationContext)
        {
            _synchronizationContext = synchronizationContext;
            synchronizationContext?.OperationStarted();

            _coreState = new AsyncMethodBuilderCore();
        }
Exemple #4
0
        internal AsyncOperation(SynchronizationContext ctx,
                                object state)
        {
            this.ctx   = ctx;
            this.state = state;

            ctx.OperationStarted();
        }
            public static void Post(SynchronizationContext synchronizationContext, SendOrPostCallback callback, object state)
            {
                Fx.Assert(synchronizationContext != null, "Null [....] Context");
                Fx.Assert(callback != null, "Null Callback");

                synchronizationContext.OperationStarted();
                synchronizationContext.Post(wrapperCallback, new PostCallbackState(synchronizationContext, callback, state));
            }
        /// <summary>Initializes a new instance of the <see cref="AsyncVoidMethodBuilder"/> struct.</summary>
        /// <param name="synchronizationContext">
        /// The synchronization context associated with this operation. This may be <see langword="null"/>.
        /// </param>
        private AsyncVoidMethodBuilder(SynchronizationContext synchronizationContext)
        {
            _synchronizationContext = synchronizationContext;
            if (synchronizationContext != null)
                synchronizationContext.OperationStarted();

            _coreState = default(AsyncMethodBuilderCore);
            _objectIdForDebugger = null;
        }
Exemple #7
0
 ActivityScopeMethodBuilder(SynchronizationContext synchronizationContext)
 {
     this.syncContext = synchronizationContext;
     this.task        = new ActivityTask();
     if (syncContext != null)
     {
         syncContext.OperationStarted();
     }
 }
Exemple #8
0
        private AsyncTaskMethodBuilder _builder; // mutable struct: must not be readonly

        /// <summary>Initializes a new <see cref="AsyncVoidMethodBuilder"/>.</summary>
        /// <returns>The initialized <see cref="AsyncVoidMethodBuilder"/>.</returns>
        public static AsyncVoidMethodBuilder Create()
        {
            SynchronizationContext sc = SynchronizationContext.CurrentNoFlow;

            sc?.OperationStarted();
            return(new AsyncVoidMethodBuilder()
            {
                _synchronizationContext = sc
            });
        }
Exemple #9
0
 /// <summary>
 /// Initializes the <see cref="T:System.Runtime.CompilerServices.AsyncVoidMethodBuilder"/>.
 /// </summary>
 /// <param name="synchronizationContext">The synchronizationContext associated with this operation. This may be null.</param>
 private AsyncVoidMethodBuilder(SynchronizationContext synchronizationContext)
 {
     m_synchronizationContext = synchronizationContext;
     if (synchronizationContext != null)
     {
         synchronizationContext.OperationStarted();
     }
     m_coreState           = new AsyncMethodBuilderCore();
     m_objectIdForDebugger = null;
 }
Exemple #10
0
        public override void OperationStarted()
        {
            var count = _control.StartViewInUse();

            if (count != -1)
            {
                _context.OperationStarted();
                Logger.Info("SecondaryViewSynchronizationContextDecorator : OperationStarted: " + count);
            }
        }
Exemple #11
0
        /// <summary>
        /// Initializes the <see cref="T:System.Runtime.CompilerServices.AsyncVoidMethodBuilder"/>.
        /// </summary>
        /// <param name="synchronizationContext">The synchronizationContext associated with this operation. This may be null.</param>
        private AsyncVoidMethodBuilder(SynchronizationContext synchronizationContext)
        {
            _synchronizationContext = synchronizationContext;
            if (synchronizationContext != null)
            {
                synchronizationContext.OperationStarted();
            }

            _coreState = new AsyncMethodBuilderCore();
        }
 public sealed override void OperationStarted()
 {
     if (m_passThroughSyncContext != null)
     {
         m_passThroughSyncContext.OperationStarted();
     }
     else
     {
         base.OperationStarted();
     }
 }
Exemple #13
0
        public static AsyncVoidMethodBuilder Create()
        {
            SynchronizationContext currentNoFlow = SynchronizationContext.CurrentNoFlow;

            if (currentNoFlow != null)
            {
                currentNoFlow.OperationStarted();
            }
            return(new AsyncVoidMethodBuilder
            {
                m_synchronizationContext = currentNoFlow
            });
        }
        private AsyncTaskMethodBuilder _builder; // mutable struct: must not be readonly

        /// <summary>Initializes a new <see cref="AsyncVoidMethodBuilder"/>.</summary>
        /// <returns>The initialized <see cref="AsyncVoidMethodBuilder"/>.</returns>
        public static AsyncVoidMethodBuilder Create()
        {
            SynchronizationContext?sc = SynchronizationContext.Current;

            sc?.OperationStarted();

            // _builder should be initialized to AsyncTaskMethodBuilder.Create(), but on coreclr
            // that Create() is a nop, so we can just return the default here.
            return(new AsyncVoidMethodBuilder()
            {
                _synchronizationContext = sc
            });
        }
Exemple #15
0
                public override void Run(IObservable <TSource> source)
                {
                    //
                    // The interactions with OperationStarted/OperationCompleted below allow
                    // for test frameworks to wait until a whole sequence is observed, running
                    // asserts on a per-message level. Also, for ASP.NET pages, the use of the
                    // built-in synchronization context would allow processing to finished in
                    // its entirety before moving on with the page lifecycle.
                    //
                    _context.OperationStarted();

                    SetUpstream(source.SubscribeSafe(this));
                }
 public override void OperationStarted()
 {
     try
     {
         var count = control.StartViewInUse();
         this.Log("SecondaryViewSynchronizationContextDecorator : OperationStarted: " + count);
         context.OperationStarted();
     }
     catch (ViewLifeTimeException)
     {
         //Don't need to do anything, operation can't be started
     }
 }
Exemple #17
0
        public void SynchronizationContext_Create()
        {
            // 获取当前线程的同步上下文
            SynchronizationContext context = SynchronizationContext.Current;

            context.OperationStarted();                                 // 空方法, 在派生类中重写以响应操作 开始 执行的回调
            context.OperationCompleted();                               // 空方法, 在派生类中重写以响应操作 完成 执行的回调
            var b = context.IsWaitNotificationRequired();               // 确定是否等待通知

            // SendOrPostCallback - Action<object> - 表示在消息即将被调度到同步上下文时要调用的方法。
            //context.Post((SendOrPostCallback)null, (object)null);	// 在派生类中重写, 将异步消息分派到同步上下文
            //context.Send((SendOrPostCallback)null, (object)null);
            //context.Wait((IntPtr[])null, waitAll: true, millisecondsTimeout: 1000);	// 等待数组中的任意元素或所有元素接收信号
        }
Exemple #18
0
                public IDisposable Run(IObservable <TSource> source)
                {
                    //
                    // The interactions with OperationStarted/OperationCompleted below allow
                    // for test frameworks to wait until a whole sequence is observed, running
                    // asserts on a per-message level. Also, for ASP.NET pages, the use of the
                    // built-in synchronization context would allow processing to finished in
                    // its entirety before moving on with the page lifecycle.
                    //
                    _context.OperationStarted();

                    var d = source.SubscribeSafe(this);
                    var c = Disposable.Create(_context.OperationCompleted);

                    return(StableCompositeDisposable.Create(d, c));
                }
Exemple #19
0
        public static TResult InvokeWithContext <TResult>(this Func <TResult> function)
        {
            Contract.Requires <ArgumentNullException>(function != null);

            ExecutionContext       executionContext       = ExecutionContext.Capture();
            SynchronizationContext synchronizationContext = SynchronizationContext.Current;

            TaskCompletionSource <TResult> taskCompletionSource = new TaskCompletionSource <TResult>();

            try
            {
                if (synchronizationContext == null)
                {
                    TResult result = function.InvokeWith(executionContext);
                    taskCompletionSource.SetResult(result);
                }
                else
                {
                    // See: System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Create()
                    synchronizationContext.OperationStarted();
                    // See: System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.PostAction()
                    synchronizationContext.Post(_ =>
                    {
                        try
                        {
                            TResult result = function.InvokeWith(executionContext);
                            // See: System.Runtime.CompilerServices.AsyncVoidMethodBuilder.NotifySynchronizationContextOfCompletion()
                            synchronizationContext.OperationCompleted();
                            taskCompletionSource.SetResult(result);
                        }
                        catch (Exception exception)
                        {
                            taskCompletionSource.SetException(exception);
                        }
                    }, null);
                }
            }
            catch (Exception exception)
            {
                taskCompletionSource.SetException(exception);
            }

            taskCompletionSource.Task.Wait();
            return(taskCompletionSource.Task.Result);
        }
Exemple #20
0
        public static Task <TResult> InvokeWith <TResult>(this Func <TResult> function, SynchronizationContext synchronizationContext, ExecutionContext executionContext)
        {
            function.NotNull(nameof(function));

            TaskCompletionSource <TResult> taskCompletionSource = new TaskCompletionSource <TResult>();

            try
            {
                if (synchronizationContext == null)
                {
                    TResult result = function.InvokeWith(executionContext);
                    taskCompletionSource.SetResult(result);
                }
                else
                {
                    // See: System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Create()
                    synchronizationContext.OperationStarted();

                    // See: System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.PostAction()
                    synchronizationContext.Post(
                        _ =>
                    {
                        try
                        {
                            TResult result = function.InvokeWith(executionContext);

                            // See: System.Runtime.CompilerServices.AsyncVoidMethodBuilder.NotifySynchronizationContextOfCompletion()
                            synchronizationContext.OperationCompleted();
                            taskCompletionSource.SetResult(result);
                        }
                        catch (Exception exception)
                        {
                            taskCompletionSource.SetException(exception);
                        }
                    },
                        null);
                }
            }
            catch (Exception exception)
            {
                taskCompletionSource.SetException(exception);
            }

            return(taskCompletionSource.Task);
        }
Exemple #21
0
        public ThreadContext(string name, SynchronizationContext context = null)
        {
            Name    = name;
            Awaiter = new ThreadContextAwaiter(this);

            if (context == null)
            {
                Context = new SynContext(this);
                Context.OperationStarted();
                Task.Run(Execute);
            }
            else
            {
                Context = context;
            }

            Id = Context.GetHashCode();
        }
        public static void PostWithStartComplete(this SynchronizationContext context, Action action)
        {
            context.OperationStarted();

            context.Post(
                _ =>
            {
                try
                {
                    action();
                }
                finally
                {
                    context.OperationCompleted();
                }
            },
                null
                );
        }
        public static void PostWithStartComplete <T>(this SynchronizationContext context, Action <T> action, T state)
        {
            context.OperationStarted();

            context.Post(
                o =>
            {
                try
                {
                    action((T)o);
                }
                finally
                {
                    context.OperationCompleted();
                }
            },
                state
                );
        }
Exemple #24
0
        public static AsyncVoidMethodBuilder Create()
        {
            SynchronizationContext sc = SynchronizationContext.Current;

            if (sc != null)
            {
                sc.OperationStarted();
            }
            // On ProjectN we will eagerly initalize the task and it's Id if the debugger is attached
            AsyncVoidMethodBuilder avmb = new AsyncVoidMethodBuilder()
            {
                m_synchronizationContext = sc
            };

            avmb.m_task = avmb.GetTaskIfDebuggingEnabled();
            if (avmb.m_task != null)
            {
                int i = avmb.m_task.Id;
            }
            return(avmb);
        }
Exemple #25
0
        private void PostContinuation(SeqContinuationUC context, object testArg)
        {
            Task t;

            if (context == SeqContinuationUC.OnCapturedContext)
            {
                if (SynchronizationContext != null)
                {
                    SynchronizationContext.OperationStarted();
                    SynchronizationContext.Post(ExecuteContinuation, testArg);
                    return;
                }

                if (TaskScheduler != null)
                {
                    t = Task.Factory.StartNew(ExecuteContinuation, testArg, CancellationToken.None, SafeStartNewOptions(), TaskScheduler);
                    TaskRegister.RegisterTask(t);
                    return;
                }

                Trace.WriteLine("Unknown synchronization context, defaulting to TaskScheduler.Default!");
                t = Task.Factory.StartNew(ExecuteContinuation, testArg, CancellationToken.None, SafeStartNewOptions(), TaskScheduler.Default);
                TaskRegister.RegisterTask(t);
                return;
            }

            if (context == SeqContinuationUC.OnNewContext)
            {
                t = Task.Factory.StartNew(ExecuteContinuation, testArg, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
                TaskRegister.RegisterTask(t);
                return;
            }

            if (context == SeqContinuationUC.OnCallersContext)
            {
                ExecuteContinuation(testArg);
            }

            throw new InvalidOperationException($"{nameof(PostContinuation)} did not captured any context in production code");
        }
Exemple #26
0
        /// <summary>
        /// Posts the specified action to the <paramref name="synchronizationContext"/> asynchronously.
        /// </summary>
        /// <param name="synchronizationContext">The synchronization context.</param>
        /// <param name="action">The action.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// </exception>
        public static Task PostAsync(this SynchronizationContext synchronizationContext, Action action, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (synchronizationContext == null)
            {
                throw new ArgumentNullException(nameof(synchronizationContext));
            }
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            var taskCompletionSource = new TaskCompletionSource();

            synchronizationContext.OperationStarted();
            synchronizationContext.Post(state =>
            {
                try
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    action();

                    cancellationToken.ThrowIfCancellationRequested();
                    taskCompletionSource.SetResult();
                }
                catch (OperationCanceledException)
                {
                    taskCompletionSource.SetCanceled();
                }
                catch (Exception exception)
                {
                    taskCompletionSource.SetException(exception);
                }
                finally
                {
                    synchronizationContext.OperationCompleted();
                }
            }, null);

            return(taskCompletionSource.Task);
        }
Exemple #27
0
        /// <summary>
        /// Posts the specified function to the <paramref name="synchronizationContext" /> asynchronously and returns its result.
        /// </summary>
        /// <typeparam name="TState">The type of the <paramref name="state"/> parameter.</typeparam>
        /// <typeparam name="TResult">The type of the result.</typeparam>
        /// <param name="synchronizationContext">The synchronization context.</param>
        /// <param name="func">The function.</param>
        /// <param name="state">The state.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">
        /// synchronizationContext
        /// or
        /// func
        /// </exception>
        /// <exception cref="System.ArgumentNullException"></exception>
        public static Task <TResult> PostAsync <TState, TResult>(this SynchronizationContext synchronizationContext, Func <TState, TResult> func, TState state, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (synchronizationContext == null)
            {
                throw new ArgumentNullException(nameof(synchronizationContext));
            }
            if (func == null)
            {
                throw new ArgumentNullException(nameof(func));
            }

            var taskCompletionSource = new TaskCompletionSource <TResult>();

            synchronizationContext.OperationStarted();
            synchronizationContext.Post(o =>
            {
                try
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var result = func((TState)o);

                    cancellationToken.ThrowIfCancellationRequested();
                    taskCompletionSource.SetResult(result);
                }
                catch (OperationCanceledException)
                {
                    taskCompletionSource.SetCanceled();
                }
                catch (Exception exception)
                {
                    taskCompletionSource.SetException(exception);
                }
                finally
                {
                    synchronizationContext.OperationCompleted();
                }
            }, state);

            return(taskCompletionSource.Task);
        }
Exemple #28
0
    public static async Task DoProgress(this ProgressBar progressBar, int sleepTimeMiliseconds)
    {
        int sleepInterval = 50;
        int progressSteps = sleepTimeMiliseconds / sleepInterval;     //every 50ms feedback

        progressBar.Maximum = progressSteps;
        SynchronizationContext synchronizationContext = SynchronizationContext.Current;
        await Task.Run(() =>
        {
            synchronizationContext.OperationStarted();
            for (int i = 0; i <= progressSteps; i++)
            {
                Thread.Sleep(sleepInterval);
                synchronizationContext.Post(new SendOrPostCallback(o =>
                {
                    Trace.WriteLine((int)o + "%");
                    progressBar.Value = (int)o;
                }), i);
            }
            synchronizationContext.OperationCompleted();
        });
    }
Exemple #29
0
        /// <summary>
        /// Wraps the source sequence in order to run its observer callbacks on the specified synchronization context.
        /// </summary>
        /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
        /// <param name="source">Source sequence.</param>
        /// <param name="context">Synchronization context to notify observers on.</param>
        /// <returns>The source sequence whose observations happen on the specified synchronization context.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="context"/> is null.</exception>
        public static IObservable <TSource> ObserveOn <TSource>(IObservable <TSource> source, SynchronizationContext context)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

#if !NO_PERF
            return(new ObserveOn <TSource>(source, context));
#else
            return(new AnonymousObservable <TSource>(observer =>
            {
                context.OperationStarted();

                return source.Subscribe(
                    x => context.Post(_ =>
                {
                    observer.OnNext(x);
                }, null),
                    exception => context.Post(_ =>
                {
                    observer.OnError(exception);
                }, null),
                    () => context.Post(_ =>
                {
                    observer.OnCompleted();
                }, null)
                    ).Finally(() =>
                {
                    context.OperationCompleted();
                });
            }));
#endif
        }
        private void BindCore(ref MessageRpc rpc, bool startOperation)
        {
            SynchronizationContext syncContext = GetSyncContext(rpc.InstanceContext);

            if (syncContext != null)
            {
                IResumeMessageRpc resume = rpc.Pause();
                if (startOperation)
                {
                    syncContext.OperationStarted();
                    syncContext.Post(ThreadAffinityStartCallbackDelegate, resume);
                }
                else
                {
                    syncContext.Post(ThreadAffinityEndCallbackDelegate, resume);
                }
            }
            else if (rpc.SwitchedThreads)
            {
                IResumeMessageRpc resume = rpc.Pause();
                ActionItem.Schedule(ThreadBehavior.CleanThreadCallbackDelegate, resume);
            }
        }