/// <summary> /// Makes the certificate internal. /// </summary> /// <param name="subject">The s subject cn.</param> /// <param name="isRoot">if set to <c>true</c> [is root].</param> /// <param name="switchToMtaIfNeeded">if set to <c>true</c> [switch to MTA if needed].</param> /// <param name="signingCert">The signing cert.</param> /// <param name="cancellationToken">Task cancellation token</param> /// <returns>X509Certificate2.</returns> private X509Certificate2 MakeCertificateInternal(string subject, bool isRoot, bool switchToMtaIfNeeded, X509Certificate2 signingCert = null, CancellationToken cancellationToken = default(CancellationToken)) { X509Certificate2 certificate = null; if (switchToMtaIfNeeded && Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA) { using (var manualResetEvent = new ManualResetEventSlim(false)) { ThreadPool.QueueUserWorkItem(o => { certificate = MakeCertificateInternal(subject, isRoot, false, signingCert); if (!cancellationToken.IsCancellationRequested) { manualResetEvent?.Set(); } }); manualResetEvent.Wait(TimeSpan.FromMinutes(1), cancellationToken); } return(certificate); } return(MakeCertificateInternal(isRoot, subject, $"CN={subject}", DateTime.UtcNow.AddDays(-certificateGraceDays), DateTime.UtcNow.AddDays(certificateValidDays), isRoot ? null : signingCert)); }
internal void SetCompleted() { Debug.Assert(!isCompleted); isCompleted = true; callback?.Invoke(this); waitHandle?.Set(); }
// Validates init, set, reset state transitions. private static void RunManualResetEventSlimTest0_StateTrans(bool init) { ManualResetEventSlim ev = new ManualResetEventSlim(init); if (ev.IsSet != init) { Debug.WriteLine("* RunManualResetEventSlimTest0_StateTrans(init={0})", init); Assert.True(false, string.Format(" > FAILED. expected IsSet=={0}, but it's {1}", init, ev.IsSet)); } for (int i = 0; i < 50; i++) { ev.Set(); if (!ev.IsSet) { Debug.WriteLine("* RunManualResetEventSlimTest0_StateTrans(init={0})", init); Assert.True(false, string.Format(" > FAILED. expected IsSet, but it's false")); } ev.Reset(); if (ev.IsSet) { Debug.WriteLine("* RunManualResetEventSlimTest0_StateTrans(init={0})", init); Assert.True(false, string.Format(" > FAILED. expected !IsSet, but it's true")); } } }
private static void Main() { using (var manualResetEvent = new ManualResetEventSlim(false)) { Console.CancelKeyPress += (sender, eventArgs) => { Console.WriteLine("cancel!"); SetUnhealthy(); manualResetEvent?.Set(); }; try { string serviceTypeName = nameof(AwesomeApi2) + "Type"; ServiceRuntime.RegisterServiceAsync(serviceTypeName, context => new AwesomeApi2(context)).GetAwaiter().GetResult(); ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(AwesomeApi2).Name); Console.WriteLine("Running...."); manualResetEvent.Wait(); } catch (Exception e) { ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString()); throw; } } Console.WriteLine("Exiting"); }
public override void Complete() { Debug.Assert((CompletionFlags & (OperationCompletionFlags.OperationCancelled | OperationCompletionFlags.OperationFinished)) != 0); ResetOperationState(); _readNotWrite = IsReadNotWrite; var completionFlags = CompletionFlags; Saea.Complete(completionFlags); if ((completionFlags & OperationCompletionFlags.CompletedCanceledSync) == OperationCompletionFlags.CompletedCanceledSync) { // Caller threw an exception which prevents further use of this. ResetAndReturnThis(); } else { _vts.SetResult(0); ManualResetEventSlim?mre = Interlocked.Exchange(ref _mre, s_completedSentinel); // This ManualResetEventSlim is used to wait until the operation completed. // After that a direct call is made to get the result. mre?.Set(); } }
/// <summary> /// Logic that runs every time the timer hits the due time. /// </summary> /// <param name="state">The state.</param> private void InternalCallback(object state) { lock (_syncLock) { if (IsDisposed || IsDisposing) { return; } } if (_cycleDoneEvent.IsSet == false) { return; } _cycleDoneEvent.Reset(); try { _userCallback(state); } finally { _cycleDoneEvent?.Set(); _backingTimer?.Change(_period, Timeout.Infinite); } }
public async Task EmulateOfflineNetwork() { await _session.Network.Enable(new EnableCommandSettings() { MaxTotalBufferSize = 100000000 }); await _session.Network.EmulateNetworkConditions(new EmulateNetworkConditionsCommandSettings() { Offline = true, Latency = 100, DownloadThroughput = 1000, UploadThroughput = 2000, ConnectionType = ConnectionType.Cellular3g }); var loadingFailedSync = new ManualResetEventSlim(false); void NetworkEmulationHandler(object?sender, LoadingFailedEventArgs e) { Assert.That(e.ErrorText, Is.EqualTo("net::ERR_INTERNET_DISCONNECTED")); loadingFailedSync?.Set(); } _session.Network.LoadingFailed += NetworkEmulationHandler; _driver.Url = "http://thoughtworks.com"; //Added just for users to see what happens on the browser during the execution - remove it! Thread.Sleep(10000); loadingFailedSync.Wait(TimeSpan.FromSeconds(5)); }
public IEnumerable <List <T> > GetConsumingEnumerable(int maxSize) { var items = new List <T>(maxSize); while (!IsAddingCompletedAndEmpty) { if (_queue.TryDequeue(out var item)) { _hasChangedSinceLastWaitForEmpty = 1; items.Clear(); items.Add(item); while (items.Count < maxSize && _queue.TryDequeue(out item)) { items.Add(item); } yield return(items); } else { _isEmptySignal?.Set(); // a longer wait timeout decreases CPU usage and improves latency // but the guy who wrote this code is not comfortable with long timeouts in waits or sleeps if (_addSignal.Wait(200)) { _addSignal.Reset(); } } } }
public void ParticipateUntil (Task task) { ManualResetEventSlim evt = new ManualResetEventSlim (false); task.ContinueWith (_ => evt.Set (), TaskContinuationOptions.ExecuteSynchronously); ParticipateUntil (evt, -1); }
public void Close() { manualResetEvent?.Set(); lock (_closeConnLock) { if (_closed) { return; } _closed = true; } if (_currentRemoteSession != null) { try { var remote = _currentRemoteSession.Remote; remote.Shutdown(SocketShutdown.Both); remote.Close(); } catch (Exception e) { Logging.LogUsefulException(e); } } lock (_encryptionLock) { lock (_decryptionLock) { _encryptor?.Dispose(); } } }
public bool ParticipateUntil (Task task, ManualResetEventSlim evt, int millisecondsTimeout) { bool fromPredicate = true; task.ContinueWith (_ => { fromPredicate = false; evt.Set (); }, TaskContinuationOptions.ExecuteSynchronously); ParticipateUntil (evt, millisecondsTimeout); return fromPredicate; }
public void Invoke() { SynchronizationEventData tmp = this; EventLoop.OnEventExecuting(Id, ref tmp); Callback?.Invoke(State); EventLoop.OnEventExecuted(Id, tmp, EventStatus.Continue); WaitHandle?.Set(); }
internal static void Stop() { _statusUpdateThreadRunning = false; _statusUpdateThreadSleep?.Set(); if (_statusUpdateThread?.Join(UPDATE_INTERVAL) ?? false) { _statusUpdateThread?.Abort(); } _statusUpdateThread = null; }
internal static void Stop() { _nowPlayingUpdateThreadRunning = false; _nowPlayingWasSend = false; _nowPlayingUpdateThreadSleep?.Set(); if (_nowPlayingUpdateThread?.Join(UPDATE_INTERVAL) ?? false) { _nowPlayingUpdateThread?.Abort(); } _nowPlayingUpdateThread = null; }
internal override void ParticipateUntil (Task task) { if (task.IsCompleted) return; ManualResetEventSlim evt = new ManualResetEventSlim (false); task.ContinueWith (_ => evt.Set (), TaskContinuationOptions.ExecuteSynchronously); if (evt.IsSet || task.IsCompleted) return; ParticipateUntilInternal (task, evt, -1); }
public bool ParticipateUntil (Task task, ManualResetEventSlim evt, int millisecondsTimeout) { if (task.IsCompleted) return false; bool isFromPredicate = true; task.ContinueWith (_ => { isFromPredicate = false; evt.Set (); }, TaskContinuationOptions.ExecuteSynchronously); ParticipateUntilInternal (task, evt, millisecondsTimeout); return isFromPredicate; }
public void SetResult(T result, SocketError socketError, OperationCompletionFlags completionFlags) { _vts.SetResult(result); _socketError = socketError; _completionFlags = completionFlags; ManualResetEventSlim?mre = Interlocked.Exchange(ref _mre, s_completedSentinel); // This ManualResetEventSlim is used to wait until the operation completed. // After that a direct call is made to get the result. mre?.Set(); }
internal void Do() { if (Configuration.TrackOcDispatcherInvocations) { bool nestedInvocation = true; if (!DebugInfo._executingOcDispatcherInvocations.TryGetValue(_ocDispatcher._managedThreadId, out Stack <Invocation> invocations)) { nestedInvocation = false; invocations = _ocDispatcher._invocations; DebugInfo._executingOcDispatcherInvocations[_ocDispatcher._managedThreadId] = invocations; } // ReSharper disable once PossibleNullReferenceException invocations.Push(this); if (_action != null) { _action(); } else { _actionWithState(_state); } if (nestedInvocation) { invocations.Pop(); } else { DebugInfo._executingOcDispatcherInvocations.TryRemove(_ocDispatcher._managedThreadId, out _); } } else { if (_action != null) { _action(); } else { _actionWithState(_state); } } if (InvocationStatus != null) { InvocationStatus.Done = true; } _doneManualResetEvent?.Set(); }
public void Enqueue(TItem item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } lock (_syncRoot) { _items.AddLast(item); _gate?.Set(); } }
public void Run() { try { _act?.Invoke(); } catch (Exception e) { Debug.LogException(e); } _manualResetEventSlim?.Set(); }
// Validates init, set, reset state transitions. private static void RunManualResetEventSlimTest0_StateTrans(bool init) { ManualResetEventSlim ev = new ManualResetEventSlim(init); Assert.Equal(init, ev.IsSet); for (int i = 0; i < 50; i++) { ev.Set(); Assert.True(ev.IsSet); ev.Reset(); Assert.False(ev.IsSet); } }
// LiteCore finished processing X number of bytes public void CompletedReceive(ulong byteCount) { _queue.DispatchAsync(() => { if (_closed) { Log.To.Sync.V(Tag, "Already closed, ignoring call to CompletedReceive..."); return; } _receivedBytesPending -= (uint)byteCount; _receivePause?.Set(); }); }
public void Dispose() { if (!disposed) { socket?.Shutdown(SocketShutdown.Both); @event?.Set(); DisposeUtils.DisposeSafely(ref socket); DisposeUtils.DisposeSafely(ref sendEventArgs); DisposeUtils.DisposeSafely(ref receiveEventArgs); DisposeUtils.DisposeSafely(ref @event); disposed = true; } }
/// <summary> /// Stops the server operation. /// </summary> public virtual void Stop() { this.CTS?.Cancel(); _manualResetEvent?.Set(); try { _task_process_requests?.Wait(); } catch (Exception ex) when(ex.InnerException.GetType() == typeof(TaskCanceledException)) { // } }
public void DoAction() { try { action(); } catch (Exception ex) { Error = ex; } finally { waiter?.Set(); } }
public static void OnCompleted_CompletesInAnotherSynchronizationContext(bool generic, bool? continueOnCapturedContext) { SynchronizationContext origCtx = SynchronizationContext.Current; try { // Create a context that tracks operations, and set it as current var validateCtx = new ValidateCorrectContextSynchronizationContext(); Assert.Equal(0, validateCtx.PostCount); SynchronizationContext.SetSynchronizationContext(validateCtx); // Create a not-completed task and get an awaiter for it var mres = new ManualResetEventSlim(); var tcs = new TaskCompletionSource<object>(); // Hook up a callback bool postedInContext = false; Action callback = () => { postedInContext = ValidateCorrectContextSynchronizationContext.IsPostedInContext; mres.Set(); }; if (generic) { if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback); else tcs.Task.GetAwaiter().OnCompleted(callback); } else { if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback); else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback); } Assert.False(mres.IsSet, "Callback should not yet have run."); // Complete the task in another context and wait for the callback to run Task.Run(() => tcs.SetResult(null)); mres.Wait(); // Validate the callback ran and in the correct context bool shouldHavePosted = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value; Assert.Equal(shouldHavePosted ? 1 : 0, validateCtx.PostCount); Assert.Equal(shouldHavePosted, postedInContext); } finally { // Reset back to the original context SynchronizationContext.SetSynchronizationContext(origCtx); } }
internal void Execute() { Invocation originalCurrentInvocation = _ocDispatcher._currentInvocation; SynchronizationContext originalSynchronizationContext = null; if (_setSynchronizationContext) { originalSynchronizationContext = SynchronizationContext.Current; SynchronizationContext.SetSynchronizationContext( new OcDispatcherSynchronizationContext( _ocDispatcher, _priority, _context, _parent)); } if (OcConfiguration.SaveOcDispatcherInvocationExecutionStackTrace) { _executionStackTrace = Environment.StackTrace; } _executor = originalCurrentInvocation; _ocDispatcher._currentInvocation = this; _status = InvocationStatus.Executing; if (_action != null) { _action(); } else { _actionWithState(_state); } _status = InvocationStatus.Executed; if (_setSynchronizationContext) { SynchronizationContext.SetSynchronizationContext(originalSynchronizationContext); } _ocDispatcher._currentInvocation = originalCurrentInvocation; _doneManualResetEvent?.Set(); }
/// <summary> /// Stops the server and closes all open client connections. /// </summary> public void Stop() { _cts?.Cancel(); _task_accept_clients = null; _task_remove_clients = null; _manualResetEvent?.Set(); _task_process_requests?.Wait(); _tcpListener?.Stop(); _requestHandlerSet?.ForEach(requestHandler => { requestHandler.Dispose(); }); }
public static void RunManualResetEventSlimTest1_SimpleWait() { ManualResetEventSlim ev1 = new ManualResetEventSlim(false); ManualResetEventSlim ev2 = new ManualResetEventSlim(false); ManualResetEventSlim ev3 = new ManualResetEventSlim(false); Task.Run(delegate { ev2.Set(); ev1.Wait(); ev3.Set(); }); ev2.Wait(); //Thread.Sleep(100); ev1.Set(); ev3.Wait(); }
private void OnMessageReceived(object sender, Message message) { if (message.Id == Message.Id) { lock (_lock) { //if (message.Response != null) try { this.Message = message; //_response = message?.Response ?? null; _mreResponseReceived?.Set(); } catch (NullReferenceException) { } //ignore this because someone called Dispose() catch (ObjectDisposedException) { } //ignore this because someone called Dispose() } } }
} // proc Dispose protected virtual void Dispose(bool disposing) { stoppingEvent?.Set(); if (disposing) { // stop the thread if (!thread.Join(3000)) { thread.Abort(); } thread = null; // clear objects Procs.FreeAndNil(ref stoppingEvent); // Remove properties Procs.FreeAndNil(ref propertyRestarts); Procs.FreeAndNil(ref propertyRunning); } } // proc Dispose
public void Execute() { try { _action?.Invoke(); _callback?.Invoke(_state); _completionSource?.TrySetResult(null); } catch (Exception ex) { _exception = ex; _completionSource?.TrySetException(ex); throw; } finally { _isCompleted = true; _completedEvent?.Set(); } }
public void Dispose() { lock (m_syncRoot) { if (m_disposed) { return; } m_disposed = true; m_continueRead.Dispose(); m_waiting?.Set(); m_waiting = null; } try { m_notify(); } catch (Exception) { } }
public void Dispose() { if (_disposing.Value) { return; } _disposing.Value = true; _thread.Dispose(); Cancel(); //_cts.Dispose(); _mreCompleted?.Set(); _mreCompleted?.Dispose(); _mreCompleted = null; if (_genericClient != null) { _genericClient.MessageReceived -= OnMessageReceived; } _genericClient = null; GC.SuppressFinalize(this); }
public static void DeleteFileAndWait(string filepath, int timeout = 30000) { var dirName = Path.GetDirectoryName(filepath); if (dirName == null) { return; } using (var fw = new FileSystemWatcher(dirName, Path.GetFileName(filepath))) { using (var mre = new ManualResetEventSlim()) { fw.EnableRaisingEvents = true; fw.Deleted += (sender, e) => { mre?.Set(); }; File.Delete(filepath); mre.Wait(timeout); } } }
public ScriptRunner(IEnumerable <string> refs, IEnumerable <string> imps) { this.references = refs.ToList(); this.imports = imps.ToList(); this.scriptOptions = this.scriptOptions.WithReferences(refs).WithImports(imps); LinqPadExtensions.Dumped += this.LinqPadExtensionsDumped; this.queue = new ConcurrentQueue <ResultObject>(); using (var resetEvent = new ManualResetEventSlim(false)) { var uiThread = new Thread(() => { this.dispatcher = Dispatcher.CurrentDispatcher; resetEvent?.Set(); Dispatcher.Run(); }); uiThread.SetApartmentState(ApartmentState.STA); uiThread.IsBackground = true; uiThread.Start(); resetEvent.Wait(); } }
public Task CancelCallMeBack() { _callMeBackResetEvent?.Set(); return(Task.CompletedTask); }
internal void UnblockReader() { lock (this) { _blockReaderUntilRequestStreamDisposed?.Set(); } _writing = false; }
public static void BaseSynchronizationContext_SameAsNoSynchronizationContext() { var quwi = new QUWITaskScheduler(); SynchronizationContext origCtx = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); RunWithSchedulerAsCurrent(quwi, delegate { ManualResetEventSlim mres = new ManualResetEventSlim(); var tcs = new TaskCompletionSource<object>(); var awaiter = ((Task)tcs.Task).GetAwaiter(); bool ranOnScheduler = false; bool ranWithoutSyncCtx = false; awaiter.OnCompleted(() => { ranOnScheduler = (TaskScheduler.Current == quwi); ranWithoutSyncCtx = SynchronizationContext.Current == null; mres.Set(); }); Assert.False(mres.IsSet, "Callback should not yet have run."); Task.Run(delegate { tcs.SetResult(null); }); mres.Wait(); Assert.True(ranOnScheduler, "Should have run on scheduler"); Assert.True(ranWithoutSyncCtx, "Should have run with a null sync ctx"); }); } finally { SynchronizationContext.SetSynchronizationContext(origCtx); } }
public static void OnCompleted_CompletesInAnotherTaskScheduler(bool generic, bool? continueOnCapturedContext) { SynchronizationContext origCtx = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); // get off xunit's SynchronizationContext to avoid interactions with await var quwi = new QUWITaskScheduler(); RunWithSchedulerAsCurrent(quwi, delegate { Assert.True(TaskScheduler.Current == quwi, "Expected to be on target scheduler"); // Create the not completed task and get its awaiter var mres = new ManualResetEventSlim(); var tcs = new TaskCompletionSource<object>(); // Hook up the callback bool ranOnScheduler = false; Action callback = () => { ranOnScheduler = (TaskScheduler.Current == quwi); mres.Set(); }; if (generic) { if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback); else tcs.Task.GetAwaiter().OnCompleted(callback); } else { if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback); else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback); } Assert.False(mres.IsSet, "Callback should not yet have run."); // Complete the task in another scheduler and wait for the callback to run Task.Run(delegate { tcs.SetResult(null); }); mres.Wait(); // Validate the callback ran on the right scheduler bool shouldHaveRunOnScheduler = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value; Assert.Equal(shouldHaveRunOnScheduler, ranOnScheduler); }); } finally { SynchronizationContext.SetSynchronizationContext(origCtx); } }
public void ConfiguredAwaiter_OnCompleted(bool continueOnCapturedContext) { // Since ValueTask implements both OnCompleted and UnsafeOnCompleted, // OnCompleted typically won't be used by await, so we add an explicit test // for it here. ValueTask<int> t = 42; var mres = new ManualResetEventSlim(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => mres.Set()); Assert.True(mres.Wait(10000)); }
public void Awaiter_OnCompleted() { // Since ValueTask implements both OnCompleted and UnsafeOnCompleted, // OnCompleted typically won't be used by await, so we add an explicit test // for it here. ValueTask<int> t = new ValueTask<int>(42); var mres = new ManualResetEventSlim(); t.GetAwaiter().OnCompleted(() => mres.Set()); Assert.True(mres.Wait(10000)); }
public async Task ConfiguredAwaiter_ContinuesOnCapturedContext(bool continueOnCapturedContext) { await Task.Run(() => { var tsc = new TrackingSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(tsc); try { ValueTask<int> t = 42; var mres = new ManualResetEventSlim(); t.ConfigureAwait(continueOnCapturedContext).GetAwaiter().OnCompleted(() => mres.Set()); Assert.True(mres.Wait(10000)); Assert.Equal(continueOnCapturedContext ? 1 : 0, tsc.Posts); } finally { SynchronizationContext.SetSynchronizationContext(null); } }); }
private static bool TestSync() { const int RUN_TIME = 15000; const int SETUP_TIME = 20; const int CONSUM = 100; const int PRODUC = 100; const int QUEUE = 5; Thread[] consumthrs = new Thread[CONSUM]; Thread[] producthrs = new Thread[PRODUC]; int[] results = new int[PRODUC+1]; int[] consumCounters = new int[CONSUM]; int[] producCounters = new int[PRODUC]; int[] interruptCounters = new int[CONSUM + PRODUC]; int sentInterrupts = 0; ManualResetEventSlim startEvent = new ManualResetEventSlim(false); SynchronousQueue<int> sync = new SynchronousQueue<int>(); for (int i = 0; i < PRODUC; i++) { int tid = i; producthrs[i] = new Thread(() => { // Wait the start for all threads startEvent.Wait(); int endTime = Environment.TickCount + RUN_TIME; //do //{ //do //{ try { sync.Put(tid+1 , tid+1); //break; } catch (ThreadInterruptedException) { interruptCounters[tid]++; } //} while (true); //Thread.Yield(); ++producCounters[tid]; //if ((++producCounters[tid] % 1000) == 0) //{ Console.Write("[#p{0}]", tid); //} //} while (Environment.TickCount < endTime); try { Thread.Sleep(0); } catch (ThreadInterruptedException) { interruptCounters[tid]++; } }); producthrs[i].Start(); } for (int i = 0; i < CONSUM; i++) { int tid = i; consumthrs[i] = new Thread(() => { // Wait the start for all threads startEvent.Wait(); int endTime = Environment.TickCount + RUN_TIME; //do //{ //do //{ try { int result = sync.Take(tid + 1); //if (result != 0) //{ results[result] += 1; //} //break; } catch (ThreadInterruptedException) { interruptCounters[tid + CONSUM]++; } //} while (true); //Thread.Yield(); ++consumCounters[tid]; //if ((++consumCounters[tid] % 1000) == 0) //{ Console.Write("[#c{0}]", tid); //} //} while (Environment.TickCount < endTime); try { Thread.Sleep(0); } catch (ThreadInterruptedException) { interruptCounters[tid + CONSUM]++; } }); consumthrs[i].Start(); } Thread.Sleep(SETUP_TIME); startEvent.Set(); // Wait until all threads have been terminated. for (int i = 0; i < CONSUM + PRODUC; i++) { if (i < CONSUM) consumthrs[i].Join(); else producthrs[i - CONSUM].Join(); } // Show results Console.WriteLine("\nConsumers counters:"); for (int i = 0; i < CONSUM; i++) { if ((i % 5) == 0) Console.WriteLine(); Console.Write("[#c{0}: {1,4}]", i, consumCounters[i]); } Console.WriteLine("\nProducers counters:"); for (int i = 0; i < PRODUC; i++) { if ((i % 5) == 0) Console.WriteLine(); Console.Write("[#p{0}: {1,4}", i, producCounters[i]); } Console.WriteLine("\ninterrupt counters:"); int sum = 0; for (int i = 0; i < CONSUM + PRODUC; i++) { sum += interruptCounters[i]; if ((i % 5) == 0) Console.WriteLine(); Console.Write("[#{0}: {1,4}]", i, interruptCounters[i]); } Console.WriteLine("\nsent interrupts: {0}, received: {1}", sentInterrupts, sum); for (int i = 1; i < results.Count(); i++) { if (results[i] == 0) return false; Console.WriteLine(i); } return true; }
public static void RunManualResetEventSlimTest4_CombinedStateTests() { ManualResetEventSlim mres = new ManualResetEventSlim(false, 100); Assert.False(mres.IsSet, "RunManualResetEventSlimTest4_CombinedStateTests: FAILED. Set did not read correctly."); mres.Set(); Assert.True(mres.IsSet, "RunManualResetEventSlimTest4_CombinedStateTests: FAILED. Set did not write/read correctly."); }
public static void WaitNotificationTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { var tsc = new TestSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(tsc); Assert.Same(tsc, SynchronizationContext.Current); var e = new ManualResetEvent(false); tsc.WaitAction = () => e.Set(); Assert.False(tsc.IsWaitNotificationRequired()); Assert.False(e.WaitOne(0)); tsc.SetWaitNotificationRequired(); Assert.True(tsc.IsWaitNotificationRequired()); Assert.True(e.WaitOne(0)); var mres = new ManualResetEventSlim(); tsc.WaitAction = () => mres.Set(); mres.Reset(); mres.CheckedWait(); e.Reset(); tsc.WaitAction = () => e.Set(); SynchronizationContext.SetSynchronizationContext(new TestSynchronizationContext()); Assert.False(e.WaitOne(0)); SynchronizationContext.SetSynchronizationContext(tsc); Assert.True(e.WaitOne(0)); e.Reset(); e.CheckedWait(); e.Reset(); var lockObj = new object(); var lockAcquiredFromBackground = new AutoResetEvent(false); Action waitForThread; Thread t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => { lock (lockObj) { lockAcquiredFromBackground.Set(); e.CheckedWait(); } }); t.IsBackground = true; t.Start(); lockAcquiredFromBackground.CheckedWait(); Assert.True(Monitor.TryEnter(lockObj, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Monitor.Exit(lockObj); waitForThread(); e.Reset(); var m = new Mutex(); t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => { m.CheckedWait(); try { lockAcquiredFromBackground.Set(); e.CheckedWait(); } finally { m.ReleaseMutex(); } }); t.IsBackground = true; t.Start(); lockAcquiredFromBackground.CheckedWait(); m.CheckedWait(); m.ReleaseMutex(); waitForThread(); }); }
public async Task TestOrdering_Sync_OrderedDisabled() { // If ordering were enabled, this test would hang. var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2, EnsureOrdered = false }; var mres = new ManualResetEventSlim(); var tb = new TransformBlock<int, int>(i => { if (i == 0) mres.Wait(); return i; }, options); tb.Post(0); tb.Post(1); Assert.Equal(1, await tb.ReceiveAsync()); mres.Set(); Assert.Equal(0, await tb.ReceiveAsync()); tb.Complete(); await tb.Completion; }