/// <summary> /// Attempts to transition the completion state. /// </summary> public bool TrySetCompleted() { Action?continuation = null; lock (_stateSwitchLock) { if (this.IsCompleted) { return(false); } this.IsCompleted = true; continuation = _continuation; } if (continuation != null) { if (_continueOnCaptureContext) { _continuation?.Invoke(); } else { ThreadPool.QueueUserWorkItem(_triggerContinuationCallback); } } return(true); }
private void InvalidateTimerCallback(object?state) { // Check, if we have to redraw the screen if (_map?.UpdateAnimations() == true) { _refresh = true; } if (_viewport.UpdateAnimations()) { _refresh = true; } if (!_refresh) { return; } if (_drawing) { if (_performance != null) { _performance.Dropped++; } return; } _invalidate?.Invoke(); }
public async ValueTask DisposeAsync() { _cleanup?.Invoke(); _cts?.Cancel(); _logger.LogTrace($"Disposing connection loop: {_id}"); if (ExecutionTask != null) { await ExecutionTask; } }
private Sprite?SetNewAnimation(Frame[] frames, bool loop, Action?onLoopOrFinish) { if (frames.Length == 0) { done?.Invoke(); return(null); } currFrames = frames; currFrameIndex = 0; currTime = 0f; doLoop = loop; done = onLoopOrFinish; return(frames[0].sprite); }
private void StartWork() { System.Diagnostics.Debug.Assert(activeTaskAction is not null); foreach (GlobalConfig.SignatureSource repo in _repos.GetConsumingEnumerable()) { lock (_lock) { _currentRepos.Add(repo.FetchPath); } activeTaskAction(repo); lock (_lock) { _currentRepos.Remove(repo.FetchPath); CompletedTaskCount += 1; } } lock (_lock) { _activeWorkers -= 1; if (_activeWorkers == 0) { Running = false; if (CompletedTaskCount > 0) { _tasksCompleteCallback?.Invoke(); } } } }
public static T Tee <T>( this T @this, Action?action) { action?.Invoke(); return(@this); }
public void Cancel() { if (Interlocked.Exchange(ref isCancelled, 1) == 0) { _stop?.Invoke(); } }
public void Close(Action?callback) { Close((ex) => { callback?.Invoke(); }); }
public static Action <Exception?, T?> Finish <T>(TaskCompletionSource <T?> tcs, Action?callback) { bool finished = false; return((Exception? exception, T? value) => { if (finished) { return; } finished = true; callback?.Invoke(); if (exception != null) { tcs.SetException(exception); } else { tcs.SetResult(value); } }); }
public override void Execute(object parameter) { TryExecute(_action, () => { _action?.Invoke(); }); }
public void SetToIdle() { if (State == WorkState.Idle) { return; } Logger.Log("Setting database worker to Idle"); switch (State) { case WorkState.CleanSearching: break; case WorkState.Populating: m_currentTaskCancellation?.Cancel(); m_currentTaskCancellation = null; m_populateTask = m_populateSearchTask = null; break; case WorkState.Cleaning: break; } State = WorkState.Idle; m_onSetToIdleCallback?.Invoke(); m_onSetToIdleCallback = null; }
static void AnimateKineticInternal(IAnimatable self, string name, Func <double, double, bool> callback, double velocity, double drag, Action?finished = null) { var key = new AnimatableKey(self, name); AbortKinetic(key); double sign = velocity / Math.Abs(velocity); velocity = Math.Abs(velocity); int tick = Ticker.Default.Insert(step => { long ms = step; velocity -= drag * ms; velocity = Math.Max(0, velocity); var result = false; if (velocity > 0) { result = callback(sign * velocity * ms, velocity); } if (!result) { finished?.Invoke(); s_kinetics.Remove(key); } return(result); }); s_kinetics[key] = tick; }
private void When(Action when) { using (_mocks.Playback()) { when.Invoke(); } }
/// <summary> /// restarts receiver-/sending-task if they somehow crashed /// </summary> public override void Dispatch() { if (_socket == null) { return; } //Keep tasks running ... //StartReceiverTask(); StartSendingTask(); base.Dispatch(); if (FireDisconnectAction) //invoke in main thread { FireDisconnectAction = false; Disconnected?.Invoke(EDisconnectedBy.Server); Close(); // close socket } if (FireConnectFailedAction) { FireConnectFailedAction = false; ConnectFailed?.Invoke(); Close(); // close socket } }
private static Task <int> CheckCulture(CommandContext context, ExecutionDelegate next) { Action?revert = null; if (context.Tokens.TryGetDirective("culture", out string?culture)) { var name = culture !.Split(':').Last(); var cultureInfo = CultureInfo.GetCultureInfo(name); var previousCulture = CultureInfo.CurrentCulture; var previousUICulture = CultureInfo.CurrentUICulture; revert = () => { CultureInfo.CurrentCulture = previousCulture; CultureInfo.CurrentUICulture = previousUICulture; }; CultureInfo.CurrentCulture = cultureInfo; CultureInfo.CurrentUICulture = cultureInfo; } var result = next(context); // revert for tests and interactive repl sessions revert?.Invoke(); return(result); }
/// <summary> /// <para> /// Changes value of <paramref name="backingStore"/> to <paramref name="value"/> if they are not equal. /// Before changing, fires a <see cref="INotifyPropertyChanging.PropertyChanging"/> <see langword="event"/>. /// After changing, executes <paramref name="onChanged"/> if defined and then fires a <see cref="INotifyPropertyChanged.PropertyChanged"/> <see langword="event"/>. /// Returns <see langword="true"/> if changed, otherwise <see langword="false"/>. /// </para> /// <para> /// <paramref name="propertyName"/> is, using <see cref="CallerMemberNameAttribute"/>, automatically set, but can still be overridden. /// </para> /// </summary> /// <typeparam name="T">The type of the property.</typeparam> /// <param name="backingStore">The backing field of the property.</param> /// <param name="value">The value to set to the property.</param> /// <param name="onChanged">The action to execute if the property has changed.</param> /// <param name="propertyName">The name of the property.</param> protected virtual bool SetProperty <T>( #if SUPPORTSNULLATTRIBUTES [AllowNull, MaybeNull, NotNullIfNotNull("value")] #endif ref T backingStore, T value, Action?onChanged = null, [CallerMemberName] string propertyName = "") { #if NETSTANDARD2_1 // Not appropriately annotated in Dotnet2_1 #pragma warning disable CS8604 // Possible null reference argument. #endif if (EqualityComparer <T> .Default.Equals(backingStore, value)) { return(false); } #if NETSTANDARD2_1 #pragma warning restore CS8604 // Possible null reference argument. #endif Check.StringArgumentNotNullOrWhiteSpace(propertyName, nameof(propertyName)); OnPropertyChanging(propertyName); // backingStore came in as a ref parameter. // Therefore overriding the parameter here also overrides the value where this parameter value came from. backingStore = value; onChanged?.Invoke(); OnPropertyChanged(propertyName); return(true); }
public static void WriteElementBlock(this XmlWriter xmlWriter, string localName, string ns, Action<XmlWriter> action) { xmlWriter.WriteStartElement(localName, ns); action.Invoke(xmlWriter); xmlWriter.WriteEndElement(); xmlWriter.Flush(); }
private void FillDataTable(DataTable dataTable, string tableName) { Action?close = null; if (m_connection.State != ConnectionState.Open) { m_connection.Open(); close = m_connection.Close; } using (var command = m_connection.CreateCommand()) { #pragma warning disable CA2100 command.CommandText = "SELECT " + string.Join(", ", dataTable.Columns.Cast <DataColumn>().Select(x => x.ColumnName)) + " FROM INFORMATION_SCHEMA." + tableName + ";"; #pragma warning restore CA2100 using var reader = command.ExecuteReader(); while (reader.Read()) { var rowValues = new object[dataTable.Columns.Count]; reader.GetValues(rowValues); dataTable.Rows.Add(rowValues); } } close?.Invoke(); }
/// <summary> /// Registers a resource that requires the current AppDomain to be the main domain to function. /// </summary> /// <param name="install">An action to execute when registering.</param> /// <param name="release">An action to execute before the AppDomain releases the main domain status.</param> /// <param name="weight">An optional weight (lower goes first).</param> /// <returns>A value indicating whether it was possible to register.</returns> /// <remarks>If registering is successful, then the <paramref name="install"/> action /// is guaranteed to execute before the AppDomain releases the main domain status.</remarks> public bool Register(Action?install = null, Action?release = null, int weight = 100) { lock (_locko) { if (_signaled) { return(false); } if (_isMainDom.HasValue == false) { throw new InvalidOperationException("Register called before IsMainDom has been established"); } else if (_isMainDom == false) { _logger.LogWarning("Register called when MainDom has not been acquired"); return(false); } install?.Invoke(); if (release != null) { _callbacks.Add(new KeyValuePair <int, Action>(weight, release)); } return(true); } }
public void Dispose() { // Prevent double-dispose, and null field out on dispose Action?action = Interlocked.Exchange(ref _onDispose, null); action?.Invoke(); }
> GetAnalysisResultAsync( DocumentAnalysisScope analysisScope, CancellationToken cancellationToken ) { RoslynDebug.Assert(_compilationWithAnalyzers != null); try { var resultAndTelemetry = await _diagnosticAnalyzerRunner .AnalyzeDocumentAsync( analysisScope, _compilationWithAnalyzers, _logPerformanceInfo, getTelemetryInfo : false, cancellationToken ) .ConfigureAwait(false); return(resultAndTelemetry.AnalysisResult); } catch { _onAnalysisException?.Invoke(); throw; } }
protected ICommand BindToEvent <TEvent>(Func <IListManager, TEvent?> exec, Func <IListManager, bool>?canExec = null, Action?postExec = null) where TEvent : class { var manager = _listManager; // ReSharper disable once ImplicitlyCapturedClosure async void Exec(object arg) => await Task.Run(() => { var e = exec(manager); if (e == null) { return; } _eventSystem.Publish(e); postExec?.Invoke(); }); // ReSharper disable once ImplicitlyCapturedClosure bool CanExec(object arg) => canExec == null || canExec(manager); return(new DelegateCommand(Exec, CanExec)); }
public void OnCompleted(Action continuation) { // Set continuation action and read IsCompleted flag var isCompleted = false; lock (_stateSwitchLock) { if (_continuation != null) { throw new InvalidOperationException("This ReusableAwaiter instance has already been listened"); } _continuation = continuation; isCompleted = this.IsCompleted; } // Call the continuation directly if the awaiter was completed before if (isCompleted) { if (_continueOnCaptureContext) { _continuation?.Invoke(); } else { ThreadPool.QueueUserWorkItem(_triggerContinuationCallback); } } }
private static async IAsyncEnumerable <TSource> DoCore <TSource>(IAsyncEnumerable <TSource> source, Action <TSource> onNext, Action <Exception>?onError, Action?onCompleted, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default) { await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false); while (true) { TSource item; try { if (!await e.MoveNextAsync()) { break; } item = e.Current; onNext(item); } catch (OperationCanceledException) { throw; } catch (Exception ex) when(onError != null) { onError(ex); throw; } yield return(item); } onCompleted?.Invoke(); }
public async Task RunAsync(Action?onWatchlistChange = null, CancellationToken cancellationToken = default) { _logger.Info("Loading stamps to watch"); // The watchlist is essentially immutable on every run. The reason is that a change to the Watchlist // likely triggers a change in the scheduled rules, so we need to regenerate the entire schedule. var watchlist = await Watchlist.CreateAsync(_logger, _cslQueryProvider, _configuration.Environments); _logger.Info("Creating rules schedule"); CreateSchedule(watchlist); if (onWatchlistChange != null) { // This rule takes care of updating the watchlist and triggering the action when it has effectively // changed. The action will take care of restarting the entire application. _scheduler.Add(new LambdaRule( identifier: "WatchlistUpdate", concurrencyBucket: "Kusto", lambda: async(context) => { if (await watchlist.RefreshAsync()) { onWatchlistChange?.Invoke(); } }), TimeSpan.FromMinutes(30)); } _logger.Info("Entering scheduler loop"); await _scheduler.RunAsync(cancellationToken); }
/// <summary> /// /// </summary> protected override void OnPreviewMouseWheel(MouseState mouseState, ref bool handled) { if (mouseState.IsCtrl) { _zoomLevel += mouseState.WheelNotchY; #warning とりあえず _zoomLevel = MathUtil.Clamp(_zoomLevel, -10, 22); ZoomRate = Math.Pow(1.1, _zoomLevel); AsciiFont.Dispose(); AsciiFont = CanvasContext.CreateFont(_settings.fonts.asciiFont.name, _settings.fonts.asciiFont.height * ZoomRate); JpFont.Dispose(); JpFont = CanvasContext.CreateFont(_settings.fonts.jpFont.name, _settings.fonts.jpFont.height * ZoomRate); UpdateLayout(); FontChanged?.Invoke(); } else { if (mouseState.IsShift) { HScrollBar.Value += mouseState.WheelNotchY * _settings.scrollSpeed_horizontal * -1; } else { VScrollBar.Value += mouseState.WheelNotchY * _settings.scrollSpeed_vertical * -1; } } handled = true; }
#pragma warning disable S3168 // "async" methods should not return "void" /// <summary> /// Fires the and forget safe asynchronous. /// </summary> /// <param name="task">The task.</param> /// <param name="completed">The completed.</param> /// <param name="error">The error.</param> /// <param name="final">The final.</param> /// <param name="cancel">The cancel.</param> /// <param name="configureAwait">if set to <c>true</c> [configure await].</param> /// <exception cref="System.ArgumentNullException">task is null.</exception> public static async void FireAndForgetSafeAsync( [NotNull] this Task task, Action?completed = null, Action <Exception>?error = null, Action?final = null, Action?cancel = null, bool configureAwait = false) #pragma warning restore S3168 // "async" methods should not return "void" { if (task == null) { throw new ArgumentNullException(nameof(task)); } try { await task.ConfigureAwait(configureAwait); completed?.Invoke(); } catch (TaskCanceledException) { cancel.Raise(); } catch (Exception ex) { error.Raise(ex); } finally { final.Raise(); } }
/// <summary> /// Handler the credential state for the given user. /// </summary> /// <param name="authorized">The Apple ID credential is valid handler.</param> /// <param name="credentialRevoked">The Apple ID credential is revoked handler.</param> /// <param name="credentialNotFound">No credential was found, so show the sign-in UI.</param> public void GetCredentialState( Action?authorized = null, Action?credentialRevoked = null, Action?credentialNotFound = null) { _appleIdProvider.GetCredentialState(CurrentUserIdentifier, (credentialState, error) => { switch (credentialState) { case ASAuthorizationAppleIdProviderCredentialState.Authorized: // user remain logged in, proceed to another view authorized?.Invoke(); break; case ASAuthorizationAppleIdProviderCredentialState.Revoked: // user logged in before but revoked credentialRevoked?.Invoke(); break; case ASAuthorizationAppleIdProviderCredentialState.NotFound: // user haven't log in before credentialNotFound?.Invoke(); break; case ASAuthorizationAppleIdProviderCredentialState.Transferred: break; } }); }
public async Task RunAsync(OperationContext context, Action?onWatchlistChange = null) { Tracer.Info(context, "Loading stamps to watch"); // The watchlist is essentially immutable on every run. The reason is that a change to the Watchlist // likely triggers a change in the scheduled rules, so we need to regenerate the entire schedule. var watchlist = await Watchlist.CreateAsync( _logger, _configuration.Environments, _environmentResources.ToDictionary( kvp => kvp.Key, kvp => kvp.Value.KustoQueryClient)); Tracer.Info(context, "Creating rules schedule"); CreateSchedule(watchlist); if (onWatchlistChange != null) { // This rule takes care of updating the watchlist and triggering the action when it has effectively // changed. The action will take care of restarting the entire application. _scheduler.Add(new LambdaRule( identifier: "WatchlistUpdate", concurrencyBucket: "Kusto", lambda: async(ruleContext) => { if (await watchlist.RefreshAsync()) { onWatchlistChange?.Invoke(); } }), TimeSpan.FromMinutes(30)); } Tracer.Info(context, "Entering scheduler loop"); await _scheduler.RunAsync(context.Token); }
public static async Task SendStreamAsync(Func <ReadOnlyMemory <byte>, Task> publishBuffer, Func <Task> publishBufferEnd, Stream stream, CancellationToken token, Action?started = null) { using var bo = ArrayPool <byte> .Shared.RentOwner(StreamBufferSize); var readCount = await stream.GreedReadAsync(bo.Array, 0, StreamBufferSize, token); started?.Invoke(); while (readCount > 0) { if (readCount < StreamBufferSize) { await publishBuffer(bo.Array.AsMemory().Slice(0, readCount)); await publishBufferEnd(); return; } await publishBuffer(bo.Array.AsMemory().Slice(0, readCount)); readCount = await stream.GreedReadAsync(bo.Array, 0, StreamBufferSize, token); } await publishBufferEnd(); }
private void Given(Action given) { using (_mocks.Record()) { given.Invoke(); } }
#pragma warning disable CA1068 // Method should take CancellationToken as last private static async Task <bool> TryTakeAndHold( AsyncLock asyncLock, TimeSpan holdTime, CancellationToken cancellation = default, Action?callback = null) #pragma warning restore CA1068 { try { using (await asyncLock.AcquireAsync(holdTime, cancellation)) { callback?.Invoke(); await TaskEx.Delay(holdTime).ConfigureAwait(false); } return(true); } catch (OperationCanceledException) { return(false); } catch (TimeoutException) { return(false); } }
/// <inheritdoc cref="INotificationManager.ShowAsync{TViewModel}(TViewModel, string?, TimeSpan?, Action?, Action?, CancellationToken)"/> public async Task ShowAsync <TViewModel>(TViewModel viewModel, string?areaName = null, TimeSpan?expirationTime = null, Action?onClick = null, Action?onClose = null, CancellationToken token = default) where TViewModel : INotificationViewModel { await ShowAsync(Guid.NewGuid(), viewModel, areaName, expirationTime, (i) => onClick?.Invoke(), (i) => onClose?.Invoke(), token); }
/// <summary> /// Performs configuration for <see cref="GlobalConfiguration.Configuration"/> and ensures that it is /// initialized. /// </summary> /// <param name="configurationCallback">The callback that will perform the configuration.</param> public static void Configure(Action<HttpConfiguration> configurationCallback) { if (configurationCallback == null) { throw new ArgumentNullException("configurationCallback"); } configurationCallback.Invoke(Configuration); Configuration.EnsureInitialized(); }
public static void HandleException(bool exceptionDefaultOrBeforeAwait, bool exceptionAfterAwait, Action action) { bool hasException = false; SetExceptionInjection(exceptionDefaultOrBeforeAwait, exceptionAfterAwait); try { action.Invoke(); } catch (Exception ex) { hasException = true; Debug.WriteLine("Exception: {0}", ex.Message); } AssertTransactionNull(); Assert.Equal<bool>(hasException, true); ResetExceptionInjection(); }
public async void WriteEndOfMessageAsync(Action<object> callback, object state) { if (WcfEventSource.Instance.WebSocketAsyncWriteStartIsEnabled()) { // TODO: Open bug about not emitting the hostname/port WcfEventSource.Instance.WebSocketAsyncWriteStart( _webSocket.GetHashCode(), 0, string.Empty); } var timeoutHelper = new TimeoutHelper(_closeTimeout); var cancelTokenTask = timeoutHelper.GetCancellationTokenAsync(); try { var cancelToken = await cancelTokenTask; await _webSocket.SendAsync(new ArraySegment<byte>(Array.Empty<byte>(), 0, 0), _outgoingMessageType, true, cancelToken); if (WcfEventSource.Instance.WebSocketAsyncWriteStopIsEnabled()) { WcfEventSource.Instance.WebSocketAsyncWriteStop(_webSocket.GetHashCode()); } } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } if (cancelTokenTask.Result.IsCancellationRequested) { throw Fx.Exception.AsError( new TimeoutException(InternalSR.TaskTimedOutError(timeoutHelper.OriginalTimeout))); } throw WebSocketHelper.ConvertAndTraceException(ex, timeoutHelper.OriginalTimeout, WebSocketHelper.SendOperation); } finally { callback.Invoke(state); } }
internal static void HandleContinueWithTask(Task task, Action<Exception> exceptionHandler) { if (task.IsFaulted) { if (exceptionHandler == null) { throw FxTrace.Exception.AsError<FaultException>(task.Exception); } else { exceptionHandler.Invoke(task.Exception); } } else if (task.IsCanceled) { throw FxTrace.Exception.AsError(new TimeoutException(SR.GetString(SR.TaskCancelledError))); } }
private async void HandleSendAsyncCompletion(Task task, TimeSpan timeout, Action<object> callback, object state) { try { await task; } catch (Exception) { _pendingWritingMessageException = WebSocketHelper.CreateExceptionOnTaskFailure(task, timeout, WebSocketHelper.SendOperation); } finally { if (WcfEventSource.Instance.WebSocketAsyncWriteStopIsEnabled()) { WcfEventSource.Instance.WebSocketAsyncWriteStop(WebSocket.GetHashCode()); } callback.Invoke(state); } }
private static IHostPrincipalService CreatePrincipalService( Action<IPrincipal, HttpRequestMessage> setCurrentPrincipal) { Mock<IHostPrincipalService> mock = new Mock<IHostPrincipalService>(); mock.Setup(s => s.GetCurrentPrincipal(It.IsAny<HttpRequestMessage>())).Returns(CreateDummyPrincipal()); mock.Setup(s => s.SetCurrentPrincipal(It.IsAny<IPrincipal>(), It.IsAny<HttpRequestMessage>())) .Callback<IPrincipal, HttpRequestMessage>((p, r) => { setCurrentPrincipal.Invoke(p, r); }); return mock.Object; }
private static IAuthenticationFilter CreateAuthenticationFilterChallenge( Action<HttpAuthenticationChallengeContext, CancellationToken> challenge) { Mock<IAuthenticationFilter> mock = new Mock<IAuthenticationFilter>(); mock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(), It.IsAny<CancellationToken>())) .Returns(() => Task.FromResult<object>(null)); mock.Setup(f => f.ChallengeAsync(It.IsAny<HttpAuthenticationChallengeContext>(), It.IsAny<CancellationToken>())) .Callback<HttpAuthenticationChallengeContext, CancellationToken>((c, t) => { challenge.Invoke(c, t); }) .Returns(() => Task.FromResult<object>(null)); return mock.Object; }
private static void TestExceptionFilter(ApiController controller, Exception expectedException, Action<HttpConfiguration> configure) { // Arrange Exception actualException = null; IHttpRouteData routeData = new HttpRouteData(new HttpRoute()); using (HttpRequestMessage request = new HttpRequestMessage()) using (HttpConfiguration configuration = new HttpConfiguration()) using (HttpResponseMessage response = new HttpResponseMessage()) { HttpControllerContext context = new HttpControllerContext(configuration, routeData, request); HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(configuration, "Ignored", controller.GetType()); context.Controller = controller; context.ControllerDescriptor = controllerDescriptor; if (configure != null) { configure.Invoke(configuration); } Mock<IExceptionFilter> spy = new Mock<IExceptionFilter>(); spy.Setup(f => f.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(), It.IsAny<CancellationToken>())).Returns<HttpActionExecutedContext, CancellationToken>( (c, i) => { actualException = c.Exception; c.Response = response; return Task.FromResult<object>(null); }); configuration.Filters.Add(spy.Object); // Act HttpResponseMessage ignore = controller.ExecuteAsync(context, CancellationToken.None).Result; } // Assert Assert.Same(expectedException, actualException); }
private void OnDesignPanelFirstTimeActivated(Action<XRDesignPanel> handler) { DesignMdiController.DesignPanelLoaded += (sender1, designLoadedArgs) => { var designPanel = (XRDesignPanel)sender1; EventHandler activated = null; activated = (sender2, emptyArgs) => { // remove handler after the first time it is activated designLoadedArgs.DesignerHost.Activated -= activated; handler.Invoke(designPanel); }; designLoadedArgs.DesignerHost.Activated += activated; }; }
private void Then(Action then) { _mocks.ReplayAll(); then.Invoke(); }
IEnumerator DelayAction(Action act, float delay) { yield return new WaitForSeconds(delay); act.Invoke(); }
private static ITraceWriter CreateTracer(Action<TraceRecord> trace) { Mock<ITraceWriter> mock = new Mock<ITraceWriter>(MockBehavior.Strict); TraceRecord record = null; mock.Setup(t => t.Trace(It.IsAny<HttpRequestMessage>(), It.IsAny<string>(), It.IsAny<TraceLevel>(), It.IsAny<Action<TraceRecord>>())) .Callback<HttpRequestMessage, string, TraceLevel, Action<TraceRecord>>((r, c, l, a) => { record = new TraceRecord(r, c, l); a.Invoke(record); trace.Invoke(record); }); return mock.Object; }
/// <summary> /// Invoke in UI thread. /// </summary> public void BeginInvoke(Action a) { a.Invoke(); }
public static void UIThread(this Control control,Action code) { if (control.InvokeRequired) { control.BeginInvoke(code); return; } code.Invoke(); }
private async void HandleCloseOutputAsyncCompletion(Task task, TimeSpan timeout, Action<object> callback, object state) { try { await task; } catch (Exception) { _pendingWritingMessageException = WebSocketHelper.CreateExceptionOnTaskFailure(task, timeout, WebSocketHelper.CloseOperation); } finally { callback.Invoke(state); } }