public void Post() { var r = new SynchronizationContext(); var n = 0; r.PostAction(() => n = 1).AssertRanToCompletion(); n.AssertEquals(1); r.PostAction(() => { throw new InvalidOperationException(); }).AssertFailed<InvalidOperationException>(); r.PostAction(() => { throw new TaskCanceledException(); }).AssertCancelled(); r.PostFunc(() => 2).AssertRanToCompletion().AssertEquals(2); r.PostFunc<int>(() => { throw new InvalidOperationException(); }).AssertFailed<InvalidOperationException>(); r.PostFunc<int>(() => { throw new TaskCanceledException(); }).AssertCancelled(); }
internal void SetSynchronizationContext(SynchronizationContext synchronizationContext) { this.syncContext = synchronizationContext; }
public UIFactTests() { this.ctorSyncContext = SynchronizationContext.Current; this.ctorThreadId = Environment.CurrentManagedThreadId; }
public SynchronizationContextContinuation(Action action, SynchronizationContext ctx, InstanceReference instanceReference, IAsyncSetThis thisSetter) { this.action = action; this.ctx = ctx; this.instanceReference = instanceReference; this.thisSetter = thisSetter; }
private static void SetSynchronizationContext(SynchronizationContext sc) { SynchronizationContext.SetSynchronizationContext(sc); }
public DelayAwaiter(float seconds) { context = SynchronizationContext.Current; this.seconds = seconds; }
public AsyncInvokeContextBase(HproseClient client, string functionName, object[] arguments, HproseErrorEvent errorCallback, Type returnType, bool byRef, HproseResultMode resultMode, bool simple) { this.client = client; this.functionName = functionName; this.arguments = arguments; this.errorCallback = (errorCallback == null) ? client.OnError : errorCallback; this.returnType = returnType; this.byRef = byRef; this.resultMode = resultMode; this.simple = simple; this.syncContext = HproseClient.SynchronizationContext; this.context = new HproseClientContext(client); }
/// <summary> /// Constructs a SynchronizationContextTaskScheduler associated with <see cref="T:System.Threading.SynchronizationContext.Current"/> /// </summary> /// <exception cref="T:System.InvalidOperationException">This constructor expects <see cref="T:System.Threading.SynchronizationContext.Current"/> to be set.</exception> internal SynchronizationContextTaskScheduler() { SynchronizationContext synContext = SynchronizationContext.Current; // make sure we have a synccontext to work with if (synContext == null) { throw new InvalidOperationException(SR.TaskScheduler_FromCurrentSynchronizationContext_NoCurrent); } m_synchronizationContext = synContext; }
public abstract void Center(bool Toggle, EventHandler <DisplayEventArgs> Display, SynchronizationContext Main);
public Main() { InitializeComponent(); _syncContext = SynchronizationContext.Current; miningBtnStart = buttonStartMining.Text; miningBtnStop = "Stop Mining"; platform64bit = ArchitectureCheck.Is64Bit(); string platformString = platform64bit ? "64bit" : "32bit"; simplewalletPath = AppDomain.CurrentDomain.BaseDirectory + @"binaries/simplewallet/" + platformString + @"/simplewallet.exe"; cpuminerPath = AppDomain.CurrentDomain.BaseDirectory + @"binaries/cpuminer/" + platformString + @"/minerd.exe"; walletPath = AppDomain.CurrentDomain.BaseDirectory + @"wallet.address.txt"; if (!File.Exists(simplewalletPath)) { MessageBox.Show("Missing " + simplewalletPath); Process.GetCurrentProcess().Kill(); } if (!File.Exists(cpuminerPath)) { MessageBox.Show("Missing " + cpuminerPath); Process.GetCurrentProcess().Kill(); } if (!File.Exists(walletPath)) { MessageBox.Show("Generating new wallet with the password: x"); GenerateWallet(); } else { ReadWalletAddress(); } var coresAvailable = Environment.ProcessorCount; for (var i = 0; i < coresAvailable; i++) { string text = (i + 1).ToString(); if (i + 1 == coresAvailable) { text += " (max)"; } comboBoxCores.Items.Add(text); } var coresConfig = INI.Value("cores"); int coresInt = comboBoxCores.Items.Count - 1; if (coresConfig != "") { int coresParsed; var parsed = int.TryParse(coresConfig, out coresParsed); if (parsed) { coresInt = coresParsed - 1; } if (coresInt + 1 > coresAvailable) { coresInt = coresAvailable - 1; } } comboBoxCores.SelectedIndex = coresInt; var poolHost = INI.Value("pool_host"); if (poolHost != "") { textBoxPoolHost.Text = poolHost; } var poolPort = INI.Value("pool_port"); if (poolPort != "") { textBoxPoolPort.Text = poolPort; } Application.ApplicationExit += (s, e) => killMiners(); }
static IInvoke_Extention() { Context = SynchronizationContext.Current; }
public TextViewWriter(SynchronizationContext context, UITextView textView) { _context = context; _textView = textView; }
public EditorFile(Server server, SynchronizationContext syncContext) { _server = server; _syncContext = syncContext; }
public EditorFiles(Server server) { _server = server; _syncContext = new SingleThreadSynchronizationContext(); }
public static void SetSynchronizationContext(SynchronizationContext syncContext) { }
public WinFormsFactTests() { ctorThread = Thread.CurrentThread; ctorSyncContext = SynchronizationContext.Current; }
public abstract void ReCenter(EventHandler <DisplayEventArgs> Display, SynchronizationContext Main);
internal AsyncInvokeContextBase(HproseClient client, string functionName, object[] arguments, HproseErrorEvent errorCallback, Type returnType, bool byRef, HproseResultMode resultMode) { this.client = client; this.functionName = functionName; this.arguments = arguments; this.errorCallback = errorCallback; this.returnType = returnType; this.byRef = byRef; this.resultMode = resultMode; this.syncContext = HproseClient.SynchronizationContext; }
public abstract void StartStream(EventHandler <FrameReadyEventArgs> OnFrame, SynchronizationContext Context, EventHandler <EventArgs> ButtonPressed);
protected virtual void ValidateSynchronizationContext( SynchronizationContext synchronizationContext ) { }
private void threadMain(object arg) { ConcurrentQueueSynchronizationContext sc = null; try { sc = new ConcurrentQueueSynchronizationContext(); this.SC = sc; SynchronizationContext.SetSynchronizationContext(sc); this.TaskFactory = new TaskFactory(this.threadStopCts.Token, TaskCreationOptions.HideScheduler | TaskCreationOptions.DenyChildAttach, TaskContinuationOptions.HideScheduler | TaskContinuationOptions.DenyChildAttach, TaskScheduler.FromCurrentSynchronizationContext() ); } catch { SynchronizationContext.SetSynchronizationContext(null); sc?.Dispose(); throw; } finally { Thread.MemoryBarrier(); ((ManualResetEventSlim)arg).Set(); } using (sc) { var stopToken = this.threadStopCts.Token; while (!stopToken.IsCancellationRequested || sc.HasPendingTasks()) { try { while (this.client.IsConnected || sc.HasPendingTasks()) { var isExec = false; isExec |= this.client.DispatchIncomingCommands(); isExec |= sc.DispatchAsyncTasks(); // 20FPS (=> 50ms) var lastSendTimeSpan = this.client.LoadBalancingPeer.ConnectionTime - Math.Max( this.client.LoadBalancingPeer.LastSendOutgoingTime, this.client.LoadBalancingPeer.LastSendAckTime ); if (lastSendTimeSpan > 50 || stopToken.IsCancellationRequested) { isExec |= this.client.SendOutgoingCommands(); } if ((isExec && !stopToken.IsCancellationRequested) || (!isExec && stopToken.IsCancellationRequested) ) { Thread.Yield(); } else if (!isExec) { sc.Wait(10, stopToken); } } sc.Wait(stopToken); } catch (OperationCanceledException) { } catch { this.client.Disconnect(DisconnectCause.Exception); } } } }
internal SynchronizationStack CloneFor(SynchronizationContext ctx) { SynchronizationStack stack = new SynchronizationStack(ctx); foreach (var frame in Frames) { stack.Frames.Add(frame.Clone()); } return stack; }
public ExceptionHandlingSynchronizationContext(SynchronizationContext syncContext) { _syncContext = syncContext; }
internal static void Uninstall(bool turnOffAutoInstall) { if (AutoInstall) { WindowsFormsSynchronizationContext winFormsSyncContext = AsyncOperationManager.SynchronizationContext as WindowsFormsSynchronizationContext; if (winFormsSyncContext != null) { try { new PermissionSet(PermissionState.Unrestricted).Assert(); if (previousSyncContext == null) { AsyncOperationManager.SynchronizationContext = new SynchronizationContext(); } else { AsyncOperationManager.SynchronizationContext = previousSyncContext; } } finally { previousSyncContext = null; CodeAccessPermission.RevertAssert(); } } } if (turnOffAutoInstall) { AutoInstall = false; } }
public void PinTo(SynchronizationContext context) { // TODO 2.0 (steveb): remove implementation PinTo(new SynchronizationDispatchQueue(context)); }
public void TotalTest() { const string ErrorMessage = "TestErrorMessage"; const string WarningMessage = "TestErrorMessage"; const string ExceptionMessage = "TestException"; var exception = new Exception(ExceptionMessage); var instance = new SynchronizationContext(); instance.AddError(ErrorMessage); instance.AddWarning(WarningMessage); instance.AddException(exception); Assert.AreEqual(ErrorMessage, instance.Errors.First()); Assert.AreEqual(WarningMessage, instance.Warnings.First()); Assert.AreEqual(ExceptionMessage, instance.Exceptions.First().Message); }
/// <summary> /// Initializes an instance of the ObservableConcurrentDictionary class. /// </summary> public ObservableConcurrentDictionary() { _context = AsyncOperationManager.SynchronizationContext; _dictionary = new ConcurrentDictionary <TKey, TValue>(); }
private static IEnumerable<Task> SyncContextVerifyingEnumerable(SynchronizationContext sc) { for (int i = 0; i < 10; i++) { Assert.Same(sc, SynchronizationContext.Current); yield return TaskHelpers.Completed(); } }
public AssemblySelectionPresenter(DTE2 applicationObject, IAssemblySelectionView selectionView, SynchronizationContext uiContext) { this.uiContext = uiContext; this.applicationObject = applicationObject; this.selectionView = selectionView; this.allAssembliesSource = new CachedAssembliesSource(new AllAssembliesSource()); }
public DelayAwaiter(float seconds) { context = SynchronizationContext.Current; this.seconds = seconds; }
public HealthyProgrammerClock(SynchronizationContext synchronizationContext) { _synchronizationContext = synchronizationContext; _timer.Elapsed += Timer_Elapsed; }
internal SynchronizationContextAwaitTaskContinuation(SynchronizationContext context, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { Contract.Assert(context != null); _syncContext = context; }
public override Task <RunSummary> RunAsync(IMessageSink diagnosticMessageSink, IMessageBus messageBus, object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) { var sta = StaTaskScheduler.DefaultSta; var task = Task.Factory.StartNew(async() => { Debug.Assert(sta.Threads.Length == 1); Debug.Assert(sta.Threads[0] == Thread.CurrentThread); using (await _wpfTestSerializationGate.DisposableWaitAsync()) { try { // Sync up FTAO to the context that we are creating here. ForegroundThreadAffinitizedObject.CurrentForegroundThreadData = new ForegroundThreadData( Thread.CurrentThread, StaTaskScheduler.DefaultSta, ForegroundThreadDataKind.StaUnitTest); // Reset our flag ensuring that part of this test actually needs WpfFact s_wpfFactRequirementReason = null; // All WPF Tests need a DispatcherSynchronizationContext and we dont want to block pending keyboard // or mouse input from the user. So use background priority which is a single level below user input. var dispatcherSynchronizationContext = new DispatcherSynchronizationContext(); // xUnit creates its own synchronization context and wraps any existing context so that messages are // still pumped as necessary. So we are safe setting it here, where we are not safe setting it in test. SynchronizationContext.SetSynchronizationContext(dispatcherSynchronizationContext); // Just call back into the normal xUnit dispatch process now that we are on an STA Thread with no synchronization context. var baseTask = base.RunAsync(diagnosticMessageSink, messageBus, constructorArguments, aggregator, cancellationTokenSource); do { var delay = Task.Delay(TimeSpan.FromMilliseconds(10), cancellationTokenSource.Token); var completed = await Task.WhenAny(baseTask, delay).ConfigureAwait(false); if (completed == baseTask) { return(await baseTask.ConfigureAwait(false)); } // Schedule a task to pump messages on the UI thread. await Task.Factory.StartNew( () => WaitHelper.WaitForDispatchedOperationsToComplete(DispatcherPriority.ApplicationIdle), cancellationTokenSource.Token, TaskCreationOptions.None, sta).ConfigureAwait(false); }while (true); } finally { ForegroundThreadAffinitizedObject.CurrentForegroundThreadData = null; s_wpfFactRequirementReason = null; // Cleanup the synchronization context even if the test is failing exceptionally SynchronizationContext.SetSynchronizationContext(null); } } }, cancellationTokenSource.Token, TaskCreationOptions.None, sta); return(task.Unwrap()); }
/// <summary> /// Build mock projects for development and testing purpose. /// </summary> /// <param name="context">The context with parameters.</param> public override void BuildProjects(ILibraryBuilderContext context) { var v = new SynchronizationContext(); v.AddWarning("adf"); var path = TestFolder; if (string.IsNullOrWhiteSpace(path)) return; if (!Directory.Exists(path)) Directory.CreateDirectory(path); if ((context.LibraryType & LibraryTypes.System) != 0) { BuildServerProject( context.SourceCode.Where(c => c.Value.IsSystem).ToDictionary(c => c.Key, c => c.Value), path, Constants.SystemProcessesLibName); } if ((context.LibraryType & LibraryTypes.Custom) != 0) { BuildServerProject( context.SourceCode.Where(c => !c.Value.IsSystem).ToDictionary(c => c.Key, c => c.Value), path, Constants.ProcessesLibName, Constants.SystemProcessesLibName + ".Server"); } }
public MainForm() { InitializeComponent(); panele[0, 0] = panel1; panele[1, 0] = panel2; panele[2, 0] = panel3; panele[3, 0] = panel4; panele[0, 1] = panel5; panele[1, 1] = panel6; panele[2, 1] = panel7; panele[3, 1] = panel8; foreach (GameType gameType in Enum.GetValues(typeof(GameType))) { lbxGames.Items.Add(gameType); } if (OutputDevice.DeviceCount < 2) { DeviceOK = false; MessageBox.Show("No LPD8 = No game", "Game Over", MessageBoxButtons.OK, MessageBoxIcon.Stop); } else { try { context = SynchronizationContext.Current; outDevice1 = new OutputDevice(1); outDevice1.Error += new EventHandler <ErrorEventArgs>(inDevice_Error); } catch (Exception ex) { DeviceOK = false; MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } if (DeviceOK) { if (InputDevice.DeviceCount < 1) { DeviceOK = false; MessageBox.Show("LPD8 = No game", "Game Over", MessageBoxButtons.OK, MessageBoxIcon.Stop); } else { try { context = SynchronizationContext.Current; inDevice1 = new InputDevice(0); inDevice1.ChannelMessageReceived += HandleChannelMessageReceived; inDevice1.Error += new EventHandler <ErrorEventArgs>(inDevice_Error); AddLogDevice(0, InputDevice.GetDeviceCapabilities(0)); inDevice1.StartRecording(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop); DeviceOK = false; } } } if (DeviceOK) { ResetSquares(); } }
protected override void ValidateSynchronizationContext( SynchronizationContext synchronizationContext ) { if( !synchronizationContext.Own ) throw new DataGridInternalException( "The column is already being processed.", this.DataGridControl ); }
private static void DetectUnityThreadContext() { MainThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId; MainThreadContext = SynchronizationContext.Current; }
public SQLProfilerForm() { this.InitializeComponent(); this.synchronizationContext_0 = SynchronizationContext.Current; }
/// <inheritdoc /> public IEnumerable <string> ExportToFiles(Summary summary, ILogger consoleLogger) { DateTimeOffset startTime = DateTimeOffset.UtcNow; Exception exception = null; try { Tracer tracer = new Tracer(); foreach (var report in summary.Reports) { Span span = tracer.StartSpan("benchmarkdotnet.test", startTime: startTime); double durationNanoseconds = 0; span.SetMetric(Tags.Analytics, 1.0d); span.SetTraceSamplingPriority(SamplingPriority.AutoKeep); span.Type = SpanTypes.Test; span.ResourceName = $"{report.BenchmarkCase.Descriptor.Type.FullName}.{report.BenchmarkCase.Descriptor.WorkloadMethod.Name}"; CIEnvironmentValues.DecorateSpan(span); span.SetTag(TestTags.Name, report.BenchmarkCase.Descriptor.WorkloadMethodDisplayInfo); span.SetTag(TestTags.Type, TestTags.TypeBenchmark); span.SetTag(TestTags.Suite, report.BenchmarkCase.Descriptor.Type.FullName); span.SetTag(TestTags.Framework, $"BenchmarkDotNet {summary.HostEnvironmentInfo.BenchmarkDotNetVersion}"); span.SetTag(TestTags.Status, report.Success ? TestTags.StatusPass : TestTags.StatusFail); if (summary.HostEnvironmentInfo != null) { span.SetTag("benchmark.host.processor.name", ProcessorBrandStringHelper.Prettify(summary.HostEnvironmentInfo.CpuInfo.Value)); span.SetMetric("benchmark.host.processor.physical_processor_count", summary.HostEnvironmentInfo.CpuInfo.Value.PhysicalProcessorCount); span.SetMetric("benchmark.host.processor.physical_core_count", summary.HostEnvironmentInfo.CpuInfo.Value.PhysicalCoreCount); span.SetMetric("benchmark.host.processor.logical_core_count", summary.HostEnvironmentInfo.CpuInfo.Value.LogicalCoreCount); span.SetMetric("benchmark.host.processor.max_frequency_hertz", summary.HostEnvironmentInfo.CpuInfo.Value.MaxFrequency?.Hertz); span.SetTag("benchmark.host.os_version", summary.HostEnvironmentInfo.OsVersion.Value); span.SetTag("benchmark.host.runtime_version", summary.HostEnvironmentInfo.RuntimeVersion); span.SetMetric("benchmark.host.chronometer.frequency_hertz", summary.HostEnvironmentInfo.ChronometerFrequency.Hertz); span.SetMetric("benchmark.host.chronometer.resolution", summary.HostEnvironmentInfo.ChronometerResolution.Nanoseconds); } if (report.BenchmarkCase.Job != null) { var job = report.BenchmarkCase.Job; span.SetTag("benchmark.job.description", job.DisplayInfo); if (job.Environment != null) { var jobEnv = job.Environment; span.SetTag("benchmark.job.environment.platform", jobEnv.Platform.ToString()); if (jobEnv.Runtime != null) { span.SetTag("benchmark.job.runtime.name", jobEnv.Runtime.Name); span.SetTag("benchmark.job.runtime.moniker", jobEnv.Runtime.MsBuildMoniker); } } } if (report.ResultStatistics != null) { var stats = report.ResultStatistics; span.SetMetric("benchmark.runs", stats.N); span.SetMetric("benchmark.duration.mean", stats.Mean); span.SetMetric("benchmark.statistics.n", stats.N); span.SetMetric("benchmark.statistics.max", stats.Max); span.SetMetric("benchmark.statistics.min", stats.Min); span.SetMetric("benchmark.statistics.mean", stats.Mean); span.SetMetric("benchmark.statistics.median", stats.Median); span.SetMetric("benchmark.statistics.std_dev", stats.StandardDeviation); span.SetMetric("benchmark.statistics.std_err", stats.StandardError); span.SetMetric("benchmark.statistics.kurtosis", stats.Kurtosis); span.SetMetric("benchmark.statistics.skewness", stats.Skewness); if (stats.Percentiles != null) { span.SetMetric("benchmark.statistics.p90", stats.Percentiles.P90); span.SetMetric("benchmark.statistics.p95", stats.Percentiles.P95); span.SetMetric("benchmark.statistics.p99", stats.Percentiles.Percentile(99)); } durationNanoseconds = stats.Mean; } if (report.Metrics != null) { foreach (var keyValue in report.Metrics) { if (keyValue.Value is null || keyValue.Value.Descriptor is null) { continue; } span.SetTag($"benchmark.metrics.{keyValue.Key}.displayName", keyValue.Value.Descriptor.DisplayName); span.SetTag($"benchmark.metrics.{keyValue.Key}.legend", keyValue.Value.Descriptor.Legend); span.SetTag($"benchmark.metrics.{keyValue.Key}.unit", keyValue.Value.Descriptor.Unit); span.SetMetric($"benchmark.metrics.{keyValue.Key}.value", keyValue.Value.Value); } } if (report.BenchmarkCase.Config?.HasMemoryDiagnoser() == true) { span.SetMetric("benchmark.memory.gen0Collections", report.GcStats.Gen0Collections); span.SetMetric("benchmark.memory.gen1Collections", report.GcStats.Gen1Collections); span.SetMetric("benchmark.memory.gen2Collections", report.GcStats.Gen2Collections); span.SetMetric("benchmark.memory.total_operations", report.GcStats.TotalOperations); span.SetMetric("benchmark.memory.mean_bytes_allocations", report.GcStats.BytesAllocatedPerOperation); span.SetMetric("benchmark.memory.total_bytes_allocations", report.GcStats.GetTotalAllocatedBytes(false)); } var duration = TimeSpan.FromTicks((long)(durationNanoseconds / TimeConstants.NanoSecondsPerTick)); span.Finish(startTime.Add(duration)); } // Ensure all the spans gets flushed before we report the success. // In some cases the process finishes without sending the traces in the buffer. SynchronizationContext context = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); tracer.FlushAsync().GetAwaiter().GetResult(); } finally { SynchronizationContext.SetSynchronizationContext(context); } } catch (Exception ex) { exception = ex; consoleLogger.WriteLine(LogKind.Error, ex.ToString()); } if (exception is null) { return(new string[] { "Datadog Exporter ran successfully." }); } else { return(new string[] { "Datadog Exporter error: " + exception.ToString() }); } }
private void SynchronizeDetailSortDescriptions( SynchronizationContext synchronizationContext, DetailConfiguration detailConfiguration ) { ColumnSortCommand.ThrowIfNull( synchronizationContext, "synchronizationContext" ); ColumnSortCommand.ThrowIfNull( detailConfiguration, "detailConfiguration" ); DetailConfigurationUpdateColumnSortCommand.ThrowIfDetailsNotFlatten( detailConfiguration ); if( !synchronizationContext.Own ) return; if( !detailConfiguration.IsAttachedToDetailDescription ) return; var dataGridControl = detailConfiguration.DataGridControl; if( dataGridControl == null ) return; var rootDataGridContext = dataGridControl.DataGridContext; var masterSortDescriptions = rootDataGridContext.Items.SortDescriptions; var detailSortDescriptions = detailConfiguration.SortDescriptions; // There is nothing to synchronize. if( ( masterSortDescriptions.Count == 0 ) && ( detailSortDescriptions.Count == 0 ) ) return; using( this.DeferResortHelper( detailConfiguration ) ) { this.SynchronizeDetailSortDescriptions( masterSortDescriptions, detailSortDescriptions, detailConfiguration.ItemPropertyMap ); } }
public TCPFunctionsAsync(SynchronizationContext context, IPAddress IP, int connection_port, bool connection_active, int FixedLength) : this(context, IP, connection_port, connection_active) { fixedLength = FixedLength; }
public SynchronizationContextContinuation (Action action, SynchronizationContext ctx) { this.action = action; this.ctx = ctx; }
public TCPFunctionsAsync(SynchronizationContext context, IPEndPoint endPoint, bool connection_active) : this(context, endPoint.Address, endPoint.Port, connection_active) { }
public SynchronizationStack(SynchronizationContext ctx) { Frames = new List<SynchronizationFrame>(); this.ctx = ctx; }
private static bool IsApplicable(SynchronizationContext context) { return(context?.GetType().FullName == "System.Windows.Threading.DispatcherSynchronizationContext"); }
public new SynchronizationAction OnSynchronize(Sybase.Collections.GenericList<ISynchronizationGroup> groups, SynchronizationContext context) { return base.OnSynchronize(groups, context); //if (context == null) //{ // return Sybase.Persistence.SynchronizationAction.CANCEL; //} ////if ("my test synchronization context".Equals(context.UserContext)) ////{ //// return base.OnSynchronize(groups, context); ////} //switch (context.Status) //{ // case SynchronizationStatus.STARTING: // if (WaitForMoreChanges()) // { // return SynchronizationAction.CANCEL; // } // else // { // return SynchronizationAction.CONTINUE; // } // default: // return SynchronizationAction.CONTINUE; //} //return SynchronizationAction.CONTINUE; }
private static bool IsApplicable(SynchronizationContext context) { return(context?.GetType().FullName == "System.Windows.Forms.WindowsFormsSynchronizationContext"); }
// Instantiate and install a WF op [....] context, and save off the old one. internal static void InstallIfNeeded() { // Exit if we shouldn't auto-install, if we've already installed and we haven't uninstalled, // or if we're being called recursively (creating the WF // async op [....] context can create a parking window control). if (!AutoInstall || inSyncContextInstallation) { return; } if (SynchronizationContext.Current == null) { previousSyncContext = null; } if (previousSyncContext != null) { return; } inSyncContextInstallation = true; try { SynchronizationContext currentContext = AsyncOperationManager.SynchronizationContext; //Make sure we either have no [....] context or that we have one of type SynchronizationContext if (currentContext == null || currentContext.GetType() == typeof(SynchronizationContext)) { previousSyncContext = currentContext; // SECREVIEW : WindowsFormsSynchronizationContext.cctor generates a call to SetTopLevel on the MarshallingControl (hidden sycn hwnd), // this call demands TopLevelWindow (UIPermissionWindow.SafeTopLevelWindows) so an assert for that permission is needed here. // The assert is safe, we are creating a thread context and the [....] window is hidden. new PermissionSet(PermissionState.Unrestricted).Assert(); try { AsyncOperationManager.SynchronizationContext = new WindowsFormsSynchronizationContext(); } finally { CodeAccessPermission.RevertAssert(); } } } finally { inSyncContextInstallation = false; } }
public Progress() { context = SynchronizationContext.Current; }
public StaFactCtorSyncContextTests() { this.ctorSyncContext = new SynchronizationContext(); Assert.Null(SynchronizationContext.Current); SynchronizationContext.SetSynchronizationContext(this.ctorSyncContext); }
public DispatchWithSynchronizationContext(SynchronizationContext synchronizationContext) { _synchronizationContext = synchronizationContext; }
// Set the SynchronizationContext on the current thread public static void SetSynchronizationContext(SynchronizationContext syncContext) { s_current = syncContext; }
// Processes and invokes delegates. private void DelegateProcedure() { lock (lockObject) { // Signal the constructor that the thread is now running. Monitor.Pulse(lockObject); } // Set this DelegateQueue as the SynchronizationContext for this thread. SynchronizationContext.SetSynchronizationContext(this); // Placeholder for DelegateQueueAsyncResult objects. DelegateQueueAsyncResult result = null; // While the DelegateQueue has not been disposed. while (true) { // Critical section. lock (lockObject) { // If the DelegateQueue has been disposed, break out of loop; we're done. if (disposed) { break; } // If there are delegates waiting to be invoked. if (delegateQueue.Count > 0) { result = delegateQueue.Dequeue(); } // Else there are no delegates waiting to be invoked. else { // Wait for next delegate. Monitor.Wait(lockObject); // If the DelegateQueue has been disposed, break out of loop; we're done. if (disposed) { break; } Debug.Assert(delegateQueue.Count > 0); result = delegateQueue.Dequeue(); } } Debug.Assert(result != null); // Invoke the delegate. result.Invoke(); if (result.NotificationType == NotificationType.BeginInvokeCompleted) { InvokeCompletedEventArgs e = new InvokeCompletedEventArgs( result.Method, result.GetArgs(), result.ReturnValue, result.Error); OnInvokeCompleted(e); } else if (result.NotificationType == NotificationType.PostCompleted) { object[] args = result.GetArgs(); Debug.Assert(args.Length == 1); Debug.Assert(result.Method is SendOrPostCallback); PostCompletedEventArgs e = new PostCompletedEventArgs( (SendOrPostCallback)result.Method, args[0], result.Error); OnPostCompleted(e); } else { Debug.Assert(result.NotificationType == NotificationType.None); } } Debug.WriteLine(delegateThread.Name + " Finished"); }
public WpfFactTests() { this.ctorThread = Thread.CurrentThread; this.ctorSyncContext = SynchronizationContext.Current; }
public void TestInitialize() { _progress = 0; _cancelled = false; SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); }
/// <summary> /// Initializes an instance of the SynchronizationContextTaskScheduler class /// with the specified SynchronizationContext. /// </summary> /// <param name="context">The SynchronizationContext under which to execute tasks.</param> public SynchronizationContextTaskScheduler(SynchronizationContext context) { if (context == null) throw new ArgumentNullException("context"); _context = context; _tasks = new ConcurrentQueue<Task>(); }
/// <summary> /// Runs the poller on the caller's thread. Only returns when <see cref="Stop"/> or <see cref="StopAsync"/> are called from another thread. /// </summary> public void Run() { CheckDisposed(); if (IsRunning) { throw new InvalidOperationException("NetMQPoller is already running"); } #if NET35 m_pollerThread = Thread.CurrentThread; #else var oldSynchronisationContext = SynchronizationContext.Current; SynchronizationContext.SetSynchronizationContext(new NetMQSynchronizationContext(this)); m_isSchedulerThread.Value = true; #endif m_stopSignaler.Reset(); m_switch.SwitchOn(); try { // Recalculate all timers now foreach (var timer in m_timers) { if (timer.Enable) { timer.When = Clock.NowMs() + timer.Interval; } } // Run until stop is requested while (!m_stopSignaler.IsStopRequested) { if (m_isPollSetDirty) { RebuildPollset(); } var pollStart = Clock.NowMs(); // Set tickless to "infinity" long tickless = pollStart + int.MaxValue; // Find the When-value of the earliest timer.. foreach (var timer in m_timers) { // If it is enabled but no When is set yet, if (timer.When == -1 && timer.Enable) { // Set this timer's When to now plus it's Interval. timer.When = pollStart + timer.Interval; } // If it has a When and that is earlier than the earliest found thus far, if (timer.When != -1 && tickless > timer.When) { // save that value. tickless = timer.When; } } // Compute a timeout value - how many milliseconds from now that the earliest-timer will expire. var timeout = tickless - pollStart; // Use zero to indicate it has already expired. if (timeout < 0) { timeout = 0; } var isItemAvailable = false; if (m_pollSet.Length != 0) { isItemAvailable = m_netMqSelector.Select(m_pollSet, m_pollSet.Length, timeout); } else if (timeout > 0) { //TODO: Do we really want to simply sleep and return, doing nothing during this interval? //TODO: Should a large value be passed it will sleep for a month literally. // Solution should be different, but sleep is more natural here than in selector (timers are not selector concern). Debug.Assert(timeout <= int.MaxValue); Thread.Sleep((int)timeout); } // Get the expected end time in case we time out. This looks redundant but, unfortunately, // it happens that Poll takes slightly less than the requested time and 'Clock.NowMs() >= timer.When' // may not true, even if it is supposed to be. In other words, even when Poll times out, it happens // that 'Clock.NowMs() < pollStart + timeout' var expectedPollEnd = !isItemAvailable ? pollStart + timeout : -1L; // that way we make sure we can continue the loop if new timers are added. // timers cannot be removed foreach (var timer in m_timers) { if ((Clock.NowMs() >= timer.When || expectedPollEnd >= timer.When) && timer.When != -1) { timer.InvokeElapsed(this); if (timer.Enable) { timer.When = Clock.NowMs() + timer.Interval; } } } for (var i = 0; i < m_pollSet.Length; i++) { NetMQSelector.Item item = m_pollSet[i]; if (item.Socket != null) { NetMQSocket socket = m_pollact[i]; if (item.ResultEvent.HasError()) { if (++socket.Errors > 1) { Remove(socket); item.ResultEvent = PollEvents.None; } } else { socket.Errors = 0; } if (item.ResultEvent != PollEvents.None) { socket.InvokeEvents(this, item.ResultEvent); } } else if (item.ResultEvent.HasError() || item.ResultEvent.HasIn()) { Action <Socket> action; if (m_pollinSockets.TryGetValue(item.FileDescriptor, out action)) { action(item.FileDescriptor); } } } } } finally { try { foreach (var socket in m_sockets.ToList()) { Remove(socket); } } finally { #if NET35 m_pollerThread = null; #else m_isSchedulerThread.Value = false; SynchronizationContext.SetSynchronizationContext(oldSynchronisationContext); #endif m_switch.SwitchOff(); } } }
private static IEnumerable<Task<int>> SyncContextVerifyingEnumerable_Generic(SynchronizationContext sc) { for (int i = 0; i < 10; i++) { Assert.Same(sc, SynchronizationContext.Current); yield return TaskHelpers.FromResult(i); } }
public async Task AsyncMethod(SynchronizationContext context) { SynchronizationContext.SetSynchronizationContext(context); await Task.Delay(0); }