private void WorkerThredStart(object sender, DoScheduledWorkEventArgs args) { Exception Error = null; try { if (CancellationPending) { args.Cancel = true; } else { OnDoWork(args); } if (args.Cancel) { args.Result = null; cancellationPending = true; } } catch (Exception ex) { Error = ex; args.Result = null; } mainThreadContext.Post(workCallback, new RunWorkerCompletedEventArgs(args.Result, Error, args.Cancel)); mainThreadContext.OperationCompleted(); }
/// <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); }
protected void FireDeviceReadCompleteEvent(string deviceScannedValue) { synContext.Post(new SendOrPostCallback(delegate(object state) { if (deviceInputHandler != null && deviceInputHandler.Target != null) { if (deviceInputHandler.Target.GetType().BaseType.ToString().Contains("Form")) { System.Windows.Forms.Form f = deviceInputHandler.Target as System.Windows.Forms.Form; if (f != null && (f.IsDisposed || f.Disposing || f.Visible == false)) { UnRegister(); } } } var handler = deviceInputHandler; if (handler != null) { handler(this, new DeviceScannedEventArgs(deviceScannedValue)); } }), null); synContext.OperationCompleted(); }
public override void OperationCompleted() { inner.OperationCompleted(); if (Interlocked.Decrement(ref this.operationCount) == 0) { this.Post((ignoredState) => { this.frame.Continue = false; }, state: null); } }
protected override void Dispose(bool disposing) { if (disposing) { _context.OperationCompleted(); } base.Dispose(disposing); }
public override void OperationCompleted() { inner.OperationCompleted(); if (Interlocked.Decrement(ref this.operationCount) == 0) { this.RequestMessageLoopTermination(); } }
/// <summary>Ends the lifetime of an asynchronous operation.</summary> /// <exception cref="T:System.InvalidOperationException"> /// <see cref="M:System.ComponentModel.AsyncOperation.OperationCompleted" /> has been called previously for this task. </exception> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence" /> /// </PermissionSet> public void OperationCompleted() { if (done) { throw new InvalidOperationException("This task is already completed. Multiple call to OperationCompleted is not allowed."); } ctx.OperationCompleted(); done = true; }
public sealed override void OperationCompleted() { if (m_passThroughSyncContext != null) { m_passThroughSyncContext.OperationCompleted(); } else { base.OperationCompleted(); } }
/// <summary> /// Notifies the current synchronization context that the operation completed. /// </summary> private void NotifySynchronizationContextOfCompletion() { try { _synchronizationContext.OperationCompleted(); } catch (Exception ex) { AsyncMethodBuilderCore.ThrowOnContext(ex, null); } }
private void NotifySynchronizationContextOfCompletion() { try { m_synchronizationContext.OperationCompleted(); } catch (Exception exception) { AsyncServices.ThrowAsync(exception, null); } }
public override void OperationCompleted() { _context.OperationCompleted(); var count = _control.StopViewInUse(); if (count != -1) { Logger.Info("SecondaryViewSynchronizationContextDecorator : OperationCompleted: " + count); } }
private void SynchronizationContextEndCallback(object state) { IResumeMessageRpc resume = (IResumeMessageRpc)state; ResumeProcessing(resume); SynchronizationContext syncContext = GetSyncContext(resume.GetMessageInstanceContext()); Fx.Assert(syncContext != null, "syncContext is null !?"); syncContext.OperationCompleted(); }
private void OperationCompletedCore() { try { _syncContext.OperationCompleted(); } finally { GC.SuppressFinalize(this); } }
private void OperationCompletedCore() { try { syncContext.OperationCompleted(); } finally { alreadyCompleted = true; GC.SuppressFinalize(this); } }
public override void OperationCompleted() { try { context.OperationCompleted(); var count = control.StopViewInUse(); this.Log("SecondaryViewSynchronizationContextDecorator : OperationCompleted: " + count); } catch (ViewLifeTimeException) { //Don't need to do anything, operation can't be completed } }
/// <summary> /// Ends the lifetime of an asynchronous operation. /// </summary> /// <exception cref="InvalidOperationException"><see cref="OperationCompleted" /> has been called previously for this task.</exception> public void OperationCompleted() { EnsureNotCompleted(); try { _synchronizationContext.OperationCompleted(); } finally { _completed = true; } }
private void ExecuteContinuation(object testArg) { try { ExecutionContext.RunNullSafe(Continuation, testArg); SynchronizationContext?.OperationCompleted(); SetCompletion(); } catch (Exception ex) { ExceptionRegister.RegisterException(ex); SetException(ex); } }
/// <summary>Notifies the current synchronization context that the operation completed.</summary> private void NotifySynchronizationContextOfCompletion() { Debug.Assert(_synchronizationContext != null, "Must only be used with a non-null context."); try { _synchronizationContext.OperationCompleted(); } catch (Exception exc) { // If the interaction with the SynchronizationContext goes awry, fall back to propagating on the // thread pool. AsyncServices.ThrowAsync(exc, targetContext: null); } }
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); // 等待数组中的任意元素或所有元素接收信号 }
private void NotifySynchronizationContextOfCompletion() { if (m_synchronizationContext != null) { try { m_synchronizationContext.OperationCompleted(); } catch (Exception exc) { // If the interaction with the SynchronizationContext goes awry, // fall back to propagating on the ThreadPool. AsyncMethodBuilderCore.ThrowAsync(exc, targetContext: null); } } }
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); }
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); }
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 ); }
public static void PostWithStartComplete(this SynchronizationContext context, Action action) { context.OperationStarted(); context.Post( _ => { try { action(); } finally { context.OperationCompleted(); } }, null ); }
/// <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); }
/// <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); }
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(); }); }
/// <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 }
/// <summary> /// Sends the specified action to the <paramref name="synchronizationContext"/>. /// </summary> /// <param name="synchronizationContext">The synchronization context.</param> /// <param name="action">The action.</param> /// <exception cref="System.ArgumentNullException"> /// </exception> public static void Send(this SynchronizationContext synchronizationContext, Action action) { if (synchronizationContext == null) { throw new ArgumentNullException(nameof(synchronizationContext)); } if (action == null) { throw new ArgumentNullException(nameof(action)); } synchronizationContext.OperationStarted(); synchronizationContext.Send(_ => { try { action(); } finally { synchronizationContext.OperationCompleted(); } }, null); }
/// <summary> /// Sends the specified action to the <paramref name="synchronizationContext" />. /// </summary> /// <typeparam name="TState">The type of the <paramref name="state"/> parameter.</typeparam> /// <param name="synchronizationContext">The synchronization context.</param> /// <param name="action">The action.</param> /// <param name="state">The state to pass along.</param> /// <exception cref="ArgumentNullException"> /// synchronizationContext /// or /// action /// </exception> /// <exception cref="System.ArgumentNullException"></exception> public static void Send <TState>(this SynchronizationContext synchronizationContext, Action <TState> action, TState state) { if (synchronizationContext == null) { throw new ArgumentNullException(nameof(synchronizationContext)); } if (action == null) { throw new ArgumentNullException(nameof(action)); } synchronizationContext.OperationStarted(); synchronizationContext.Send(o => { try { action((TState)o); } finally { synchronizationContext.OperationCompleted(); } }, state); }