private static void CreateEditorInstance(EditorTestRequest a, ManualResetEventSlim evt) { try { CoreEditor = new CoreEditor(a.Text, a.FileName, a.ContentType); Window = new Window(); if (Screen.AllScreens.Length == 1) { Window.Left = 0; Window.Top = 50; } else { Screen secondary = Screen.AllScreens.FirstOrDefault(x => !x.Primary); Window.Left = secondary.WorkingArea.Left; Window.Top = secondary.WorkingArea.Top + 50; } Window.Width = 800; Window.Height = 600; Window.Title = "R Editor - " + (a.FileName ?? "Untitled"); Window.Content = CoreEditor.Control; } finally { evt.Set(); } Window.Topmost = true; Window.ShowDialog(); }
private static void CreateWindowInstance(ControlTestRequest request, ManualResetEventSlim evt) { try { Window = new Window(); if (Screen.AllScreens.Length == 1) { Window.Left = 0; Window.Top = 50; } else { Screen secondary = Screen.AllScreens.FirstOrDefault(x => !x.Primary); Window.Left = secondary.WorkingArea.Left; Window.Top = secondary.WorkingArea.Top + 50; } Window.Width = 800; Window.Height = 600; Component = Activator.CreateInstance(request.ControlType); if (Component is Control) { Control = Component as Control; } else { Control = Component.GetType().GetProperty("Control").GetValue(Component) as Control; } Window.Title = "Control - " + request.ControlType; Window.Content = Control; } finally { evt.Set(); } Window.Topmost = true; Window.ShowDialog(); }
public void Run() { _pipeHandleSet = new ManualResetEventSlim(initialState: false); Task.Run(() => Reader()); Task.Run(() => Writer()); }
public void when_sending_message_with_session_then_session_receiver_gets_it() { var sender = this.Settings.CreateTopicClient(this.Topic); var signal = new ManualResetEventSlim(); var body = Guid.NewGuid().ToString(); var receiver = new SessionSubscriptionReceiver(this.Settings, this.Topic, this.Subscription); sender.Send(new BrokeredMessage(Guid.NewGuid().ToString())); sender.Send(new BrokeredMessage(body) { SessionId = "foo" }); var received = ""; receiver.Start( m => { received = m.GetBody<string>(); signal.Set(); return MessageReleaseAction.CompleteMessage; }); signal.Wait(); receiver.Stop(); Assert.Equal(body, received); }
// Demonstrates: // ManualResetEventSlim construction // ManualResetEventSlim.Wait() // ManualResetEventSlim.Set() // ManualResetEventSlim.Reset() // ManualResetEventSlim.IsSet static void MRES_SetWaitReset() { System.Threading.ManualResetEventSlim mres1 = new System.Threading.ManualResetEventSlim(false); // initialize as unsignaled System.Threading.ManualResetEventSlim mres2 = new System.Threading.ManualResetEventSlim(false); // initialize as unsignaled System.Threading.ManualResetEventSlim mres3 = new System.Threading.ManualResetEventSlim(true); // initialize as signaled // Start an asynchronous Task that manipulates mres3 and mres2 var observer = Task.Factory.StartNew(() => { mres1.Wait(); Console.WriteLine("observer sees signaled mres1!"); Console.WriteLine("observer resetting mres3..."); mres3.Reset(); // should switch to unsignaled Console.WriteLine("observer signalling mres2"); mres2.Set(); }); Console.WriteLine("main thread: mres3.IsSet = {0} (should be true)", mres3.IsSet); Console.WriteLine("main thread signalling mres1"); mres1.Set(); // This will "kick off" the observer Task mres2.Wait(); // This won't return until observer Task has finished resetting mres3 Console.WriteLine("main thread sees signaled mres2!"); Console.WriteLine("main thread: mres3.IsSet = {0} (should be false)", mres3.IsSet); // It's good form to Dispose() a ManualResetEventSlim when you're done with it observer.Wait(); // make sure that this has fully completed mres1.Dispose(); mres2.Dispose(); mres3.Dispose(); }
// Demonstrates: // ManualResetEventSlim construction w/ SpinCount // ManualResetEventSlim.WaitHandle static void MRES_SpinCountWaitHandle() { // Construct a ManualResetEventSlim with a SpinCount of 1000 // Higher spincount => longer time the MRES will spin-wait before taking lock System.Threading.ManualResetEventSlim mres1 = new System.Threading.ManualResetEventSlim(false, 1000); System.Threading.ManualResetEventSlim mres2 = new System.Threading.ManualResetEventSlim(false, 1000); Task bgTask = Task.Factory.StartNew(() => { // Just wait a little Thread.Sleep(100); // Now signal both MRESes Console.WriteLine("Task signalling both MRESes"); mres1.Set(); mres2.Set(); }); // A common use of MRES.WaitHandle is to use MRES as a participant in // WaitHandle.WaitAll/WaitAny. Note that accessing MRES.WaitHandle will // result in the unconditional inflation of the underlying ManualResetEvent. WaitHandle.WaitAll(new WaitHandle[] { mres1.WaitHandle, mres2.WaitHandle }); Console.WriteLine("WaitHandle.WaitAll(mres1.WaitHandle, mres2.WaitHandle) completed."); // Clean up bgTask.Wait(); mres1.Dispose(); mres2.Dispose(); }
static void PrintFooBar(int p) { System.Threading.ManualResetEventSlim mres = new System.Threading.ManualResetEventSlim(false); // initialize as unsignaled System.Threading.ManualResetEventSlim mres2 = new System.Threading.ManualResetEventSlim(true); // initialize as unsignaled Thread t1 = new Thread(() => { for (int i = 0; i < 20; i++) { mres2.Wait(); Console.WriteLine("foo"); mres2.Reset(); mres.Set(); } } ); t1.Start(); Thread t2 = new Thread(() => { for (int i = 0; i < 20; i++) { mres.Wait();//true Console.WriteLine("bar"); mres.Reset(); mres2.Set(); } }); t2.Start(); }
public ETradeDispatcher(Action<Exception> errorHandler) : base(errorHandler) { const int num = 2; //num of Add() calls below var count = 0; var done = new ManualResetEventSlim(false); Action report = delegate { if (Interlocked.Increment(ref count) == num) done.Set(); }; int idmain, iddom; idmain = iddom = 0; Add(() => { idmain = Thread.CurrentThread.ManagedThreadId; report(); }, _eventThreadRequestName); Add(() => { iddom = Thread.CurrentThread.ManagedThreadId; report(); }, _eventThreadResponseName); done.Wait(); _eventThreadRequestId = idmain; _eventThreadResponseId = iddom; }
public void Ctor_ThrowsAnException_IfLockCanNotBeGranted() { var releaseLock = new ManualResetEventSlim(false); var lockAcquired = new ManualResetEventSlim(false); var thread = new Thread( () => UseConnection(connection1 => { var storage = CreateStorage(connection1); using (new SqlServerDistributedLock(storage, "exclusive", _timeout)) { lockAcquired.Set(); releaseLock.Wait(); } })); thread.Start(); lockAcquired.Wait(); UseConnection(connection2 => { var storage = CreateStorage(connection2); Assert.Throws<DistributedLockTimeoutException>( () => { using (new SqlServerDistributedLock(storage, "exclusive", _timeout)) { } }); }); releaseLock.Set(); thread.Join(); }
private System.Threading.ManualResetEventSlim slim;//主线程调用后为了判断不会第二次再进入 public SendTaskManage() { slim = new System.Threading.ManualResetEventSlim(true); // bRuning = false; downloadItems = new ConcurrentDictionary <string, DownloadItem>(System.Environment.ProcessorCount * 2, 500); mr = new ManualResetEvent(true); }
public void Initialize() { SessionService.Instance.SubscribeOnce("api_get_member/require_info", delegate { try { var rDataFile = new FileInfo(DataFilename); if (rDataFile.Exists) using (var rReader = new JsonTextReader(rDataFile.OpenText())) { var rData = JArray.Load(rReader); r_Infos = rData.Select(r => r.ToObject<ExpeditionInfo2>()).ToIDTable(); } } finally { if (r_Infos == null) r_Infos = new IDTable<ExpeditionInfo2>(); r_InitializationLock.Set(); r_InitializationLock.Dispose(); r_InitializationLock = null; } }); }
protected TcpChannel(int channelId) : base(channelId) { _receivingBufferSize = 32 * 1024; _sendingBlocking = new ManualResetEventSlim(true); _sendingCounter = new ConcurrentDictionary<long, PackingState>(); _sendingAsyncArgsPool = new SocketAsyncEventArgsPool(SocketAsyncEventArgs_Completed); }
public void continuation_error_handling_then_completion() { ManualResetEventSlim first = new ManualResetEventSlim(false), second = new ManualResetEventSlim(false), third = new ManualResetEventSlim(false); Exception ex = null; // each ContinueWith creates a new task var t = Task.Factory.StartNew(() => { first.Set(); throw new ApplicationException(); //return -5; }) .ContinueWith(tStart => { second.Set(); ex = tStart.Exception.InnerExceptions.First(); }, TaskContinuationOptions.NotOnRanToCompletion) .ContinueWith(tStart => third.Set(), TaskContinuationOptions.OnlyOnRanToCompletion); t.Wait(); Assert.IsTrue(first.IsSet); Assert.IsTrue(second.IsSet); Assert.IsTrue(third.IsSet); Assert.That(ex, Is.InstanceOf<ApplicationException>()); }
public State(int count) { signals = new ManualResetEventSlim[count]; for (int i = 0; i < signals.Length; i++) signals[i] = new ManualResetEventSlim(i == 0); }
public void Client_with_ipv6_should_connect_to_server_and_signal_appropriate_callbacks() { var connected1 = new ManualResetEventSlim(false); var connected2 = new ManualResetEventSlim(false); var ex = ServerHelpers.CreateExecutor(); var server = ServerHelpers.CreateServerIPv6(); server.Connected.Subscribe(client => { connected1.Set(); }); server.Started.Subscribe(u => { var client = new SocketClient(ex, true); client.Connected.Subscribe(_ => { connected2.Set(); }); client.Disconnected.Subscribe(exn => { throw exn; }); client.Connect(new IPEndPoint(IPAddress.IPv6Loopback, server.BindEndPoint.Port)); }); server.Start(); connected1.AssertWaitFor(5000); connected2.AssertWaitFor(5000); server.StopAndAssertStopped(); }
public void Can_create_actor_using_remote_daemon_and_interact_with_child() { var p = CreateTestProbe(); Sys.EventStream.Subscribe(p.Ref, typeof(string)); var supervisor = Sys.ActorOf<SomeActor>(); var provider = (RemoteActorRefProvider)((ActorSystemImpl)Sys).Provider; var daemon = provider.RemoteDaemon; var childCreatedEvent=new ManualResetEventSlim(); var path = (((ActorSystemImpl)Sys).Guardian.Path.Address + "/remote/user/foo").ToString(); //ask to create an actor MyRemoteActor, this actor has a child "child" daemon.Tell(new DaemonMsgCreate(Props.Create(() => new MyRemoteActor(childCreatedEvent)), null, path, supervisor)); //Wait for the child to be created (actors are instantiated async) childCreatedEvent.Wait(); //try to resolve the child actor "child" var child = provider.ResolveActorRef(provider.RootPath / "remote/user/foo/child".Split('/')); //pass a message to the child child.Tell("hello"); //expect the child to forward the message to the eventstream p.ExpectMsg("hello"); }
public void BackgroundHttpRequester_StopAsync_Stops_Current_Active_Request() { var cancelled = false; var mre = new ManualResetEventSlim(); Func<Uri, CancellationToken, bool> processor = (u, c) => { try { mre.Wait(c); } catch (AggregateException) { } catch (OperationCanceledException) { } mre.Set(); cancelled = c.IsCancellationRequested; return true; }; var requester = new BackgroundHttpFuncRequester(processor); requester.Add(TestHelpers.CreateRequestList(1)[0]); requester.Start(TimeSpan.FromMilliseconds(10)); Assert.IsFalse(cancelled); requester.StopAsync().Wait(3000); Assert.IsTrue(mre.Wait(3000)); Assert.IsTrue(cancelled); }
public static IDisposable RunConnectDisconnect(int connections) { var host = new MemoryHost(); host.MapHubs(); for (int i = 0; i < connections; i++) { var connection = new Client.Hubs.HubConnection("http://foo"); var proxy = connection.CreateHubProxy("EchoHub"); var wh = new ManualResetEventSlim(false); proxy.On("echo", _ => wh.Set()); try { connection.Start(host).Wait(); proxy.Invoke("Echo", "foo").Wait(); if (!wh.Wait(TimeSpan.FromSeconds(10))) { Debugger.Break(); } } finally { connection.Stop(); } } return host; }
public void MarkActiveStopsConnectionIfCalledAfterExtendedPeriod(HostType hostType, TransportType transportType, MessageBusType messageBusType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(messageBusType: messageBusType); var connection = CreateHubConnection(host); using (connection) { var disconnectWh = new ManualResetEventSlim(); connection.Closed += () => { disconnectWh.Set(); }; connection.Start(host.Transport).Wait(); // The MarkActive interval should check the reconnect window. Since this is short it should force the connection to disconnect. ((Client.IConnection)connection).ReconnectWindow = TimeSpan.FromSeconds(1); Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(15)), "Closed never fired"); } } }
public void PushTryPop(int producerThreads, int consumerThreads) { var stack = new ConcurrentStack<int>(); var startEvent = new ManualResetEventSlim(false); var finished = 0; var stop = false; var producerTasks = Enumerable.Range(0, producerThreads).Select(i => Task.Factory.StartNew(() => { var count = iterations/producerThreads; startEvent.Wait(); for (var j = 0; j < count; j++) stack.Push(0); Interlocked.Increment(ref finished); if (finished >= producerThreads) stop = true; }, TaskCreationOptions.LongRunning)).ToArray(); var consumerTasks = Enumerable.Range(0, consumerThreads).Select(i => Task.Factory.StartNew(() => { int num; startEvent.Wait(); while (!stop) stack.TryPop(out num); }, TaskCreationOptions.LongRunning)).ToArray(); var stopwatch = Stopwatch.StartNew(); startEvent.Set(); stop = true; Task.WaitAll(producerTasks); Task.WaitAll(consumerTasks); stopwatch.StopAndLog(iterations); }
/// <summary> /// Blocking wait for a task, equivalent to calling Task.Wait(), /// but works around a race in Mono that causes Wait() to hang /// </summary> /// <param name="task">The task to wait for</param> /// <returns>The task</returns> public static Task WaitForTask(this Task task) { // Mono has a race when waiting for a // task to complete, this workaround // ensures that the wait call does not hang if (IsRunningMono) { if (!task.IsCompleted) { using (var lck = new System.Threading.ManualResetEventSlim(false)) { task.ContinueWith(x => lck.Set()); // This ensures we never return with // an incomplete task, but may casue // some spin waiting while (!task.IsCompleted) { lck.Wait(); } } } } else { try { task.Wait(); } catch { // Don't throw the exception here // let the caller access the task } } return(task); }
static void Main() { const int taskCount = 4; var mEvents = new ManualResetEventSlim[taskCount]; var waitHandles = new WaitHandle[taskCount]; var calcs = new Calculator[taskCount]; for (int i = 0; i < taskCount; i++) { int i1 = i; mEvents[i] = new ManualResetEventSlim(false); waitHandles[i] = mEvents[i].WaitHandle; calcs[i] = new Calculator(mEvents[i]); Task.Run(() => calcs[i1].Calculation(i1 + 1, i1 + 3)); } for (int i = 0; i < taskCount; i++) { // int index = WaitHandle.WaitAny(mEvents.Select(e => e.WaitHandle).ToArray()); int index = WaitHandle.WaitAny(waitHandles); if (index == WaitHandle.WaitTimeout) { WriteLine("Timeout!!"); } else { mEvents[index].Reset(); WriteLine($"finished task for {index}, result: {calcs[index].Result}"); } } }
public void OpenCalledOnConnectionRestored() { int openInvoked = 0; var wh = new ManualResetEventSlim(); var redisConnection = GetMockRedisConnection(); var redisMessageBus = new Mock<RedisMessageBus>(GetDependencyResolver(), new RedisScaleoutConfiguration(String.Empty, String.Empty), redisConnection.Object) { CallBase = true }; redisMessageBus.Setup(m => m.OpenStream(It.IsAny<int>())).Callback(() => { // Open would be called twice - once when connection starts and once when it is restored if (++openInvoked == 2) { wh.Set(); } }); // Creating an instance to invoke the constructor which starts the connection var instance = redisMessageBus.Object; redisConnection.Raise(mock => mock.ConnectionRestored += null, new Exception()); Assert.True(wh.Wait(TimeSpan.FromSeconds(5))); }
public async void ConnectRetriesOnError() { int invokationCount = 0; var wh = new ManualResetEventSlim(); var redisConnection = GetMockRedisConnection(); var tcs = new TaskCompletionSource<object>(); tcs.TrySetCanceled(); redisConnection.Setup(m => m.ConnectAsync(It.IsAny<string>(), It.IsAny<TraceSource>())).Returns<string, TraceSource>((connectionString, trace) => { if (++invokationCount == 2) { wh.Set(); return Task.FromResult(0); } else { return tcs.Task; } }); var redisMessageBus = new RedisMessageBus(GetDependencyResolver(), new RedisScaleoutConfiguration(String.Empty, String.Empty), redisConnection.Object, false); await redisMessageBus.ConnectWithRetry(); Assert.True(wh.Wait(TimeSpan.FromSeconds(5))); Assert.Equal(RedisMessageBus.State.Connected, redisMessageBus.ConnectionState); }
public void Client_should_connect_to_server_and_signal_appropriate_callbacks() { var connected1 = new ManualResetEventSlim(false); var connected2 = new ManualResetEventSlim(false); var ex = ServerHelpers.CreateExecutor(); var server = ServerHelpers.CreateServer(); server.Connected += client => { connected1.Set(); }; server.Started += () => { var client = new SocketClient(ex); client.Connected += () => { connected2.Set(); }; client.Disconnected += exc => { throw exc; }; client.Connect(new IPEndPoint(IPAddress.Loopback, server.BindEndPoint.Port)); }; server.Start(); connected1.AssertWaitFor(3000); connected2.AssertWaitFor(3000); server.StopAndAssertStopped(); }
public void ClientStopsReconnectingAfterDisconnectTimeout(HostType hostType, TransportType transportType) { using (var host = CreateHost(hostType, transportType)) { host.Initialize(keepAlive: 1, disconnectTimeout: 2); var connection = new Client.Hubs.HubConnection(host.Url); var reconnectWh = new ManualResetEventSlim(); var disconnectWh = new ManualResetEventSlim(); connection.Reconnecting += () => { reconnectWh.Set(); Assert.Equal(ConnectionState.Reconnecting, connection.State); }; connection.Closed += () => { disconnectWh.Set(); Assert.Equal(ConnectionState.Disconnected, connection.State); }; connection.Start(host.Transport).Wait(); host.Shutdown(); Assert.True(reconnectWh.Wait(TimeSpan.FromSeconds(5))); Assert.True(disconnectWh.Wait(TimeSpan.FromSeconds(5))); } }
public WebSocket(DiscordClient client, JsonSerializer serializer, Logger logger) { _client = client; Logger = logger; _serializer = serializer; _lock = new AsyncLock(); _taskManager = new TaskManager(Cleanup); CancelToken = new CancellationToken(true); _connectedEvent = new ManualResetEventSlim(false); #if !DOTNET5_4 _engine = new WS4NetEngine(client.Config, _taskManager); #else _engine = new BuiltInEngine(client.Config); #endif _engine.BinaryMessage += (s, e) => { using (var compressed = new MemoryStream(e.Data, 2, e.Data.Length - 2)) using (var decompressed = new MemoryStream()) { using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress)) zlib.CopyTo(decompressed); decompressed.Position = 0; using (var reader = new StreamReader(decompressed)) ProcessMessage(reader.ReadToEnd()).GetAwaiter().GetResult(); } }; _engine.TextMessage += (s, e) => ProcessMessage(e.Message).Wait(); }
public override void Respond(IHttpContext context) { if (string.IsNullOrEmpty(context.Request.QueryString["no-op"]) == false) { // this is a no-op request which is there just to force the client HTTP layer to handle the authentication // only used for legacy clients return; } if("generate-single-use-auth-token".Equals(context.Request.QueryString["op"],StringComparison.InvariantCultureIgnoreCase)) { // using windows auth with anonymous access = none sometimes generate a 401 even though we made two requests // instead of relying on windows auth, which require request buffering, we generate a one time token and return it. // we KNOW that the user have access to this db for writing, since they got here, so there is no issue in generating // a single use token for them. var token = server.RequestAuthorizer.GenerateSingleUseAuthToken(Database, context.User); context.WriteJson(new { Token = token }); return; } if (HttpContext.Current != null) { HttpContext.Current.Server.ScriptTimeout = 60*60*6; // six hours should do it, I think. } var options = new BulkInsertOptions { CheckForUpdates = context.GetCheckForUpdates(), CheckReferencesInIndexes = context.GetCheckReferencesInIndexes() }; var operationId = ExtractOperationId(context); var sp = Stopwatch.StartNew(); var status = new BulkInsertStatus(); int documents = 0; var mre = new ManualResetEventSlim(false); var currentDatbase = Database; var task = Task.Factory.StartNew(() => { currentDatbase.BulkInsert(options, YieldBatches(context, mre, batchSize => documents += batchSize), operationId); status.Documents = documents; status.Completed = true; }); long id; Database.AddTask(task, status, out id); mre.Wait(Database.WorkContext.CancellationToken); context.Log(log => log.Debug("\tBulk inserted received {0:#,#;;0} documents in {1}, task #: {2}", documents, sp.Elapsed, id)); context.WriteJson(new { OperationId = id }); }
[Test] // bug https://bugzilla.novell.com/show_bug.cgi?id=325368 public void EnabledInElapsed() { var elapsedCount = 0; var mre = new ST.ManualResetEventSlim(); timer = new Timer(50); timer.AutoReset = false; timer.Elapsed += (s, e) => { elapsedCount++; if (elapsedCount == 1) { timer.Enabled = true; } else if (elapsedCount == 2) { mre.Set(); } }; timer.Start(); Assert.IsTrue(mre.Wait(1000), "#1 re-enabling timer in Elapsed didn't work"); Assert.AreEqual(2, elapsedCount, "#2 wrong elapsedCount"); timer.Stop(); }
public void events_raised_whilst_consuming_events_should_be_recorded() { var waitForConsumption = new ManualResetEventSlim(false); Transaction consumerTransaction = null; var eventStore = Substitute.For<EventStore>(); //Because consumers run in background threads, we need to block until complete before we assert. eventStore.When(_ => _.LogConsumption(Arg.Any<RaisedEvent>(), Arg.Any<ConsumptionLog>())).Do(info => { consumerTransaction = Transaction.Current; waitForConsumption.Set(); }); var domain = new TestableDomain(null, null, eventStore); var key = "test"; domain.Consume( new RaisedEvent( new DogRegistered(key, null), DateTimeOffset.UtcNow)); waitForConsumption.Wait(); var aggregateInfo = domain.AggregateTracker[typeof (Dog), key]; ((string) aggregateInfo.Instance.AsDynamic().earbrand).ShouldEqual(key); aggregateInfo.Lifestate.ShouldEqual(AggregateLifestate.Live); var recorded = domain.TransactionTracker[consumerTransaction].RecordedEvents; recorded.Count().ShouldEqual(1); recorded.First().Event.ShouldBeType<DogIsNotVaccinated>(); }
private static void FunWithMRE() { ManualResetEventSlim mre = new ManualResetEventSlim(); //MRE mre = new MRE(); mre.WaitAsync().ContinueWith(t => CW("Wait 1 complete")); mre.WaitAsync().ContinueWith(t => CW("Wait 2 complete")); mre.WaitAsync().ContinueWith(t => CW("Wait 3 complete")); WaitUntilKey("set"); mre.Set(); mre.WaitAsync().ContinueWith(t => CW("Wait 4 complete")); mre.WaitAsync().ContinueWith(t => CW("Wait 5 complete")); mre.WaitAsync().ContinueWith(t => CW("Wait 6 complete")); //WaitUntilKey("reset"); mre.Reset(); mre.WaitAsync().ContinueWith(t => CW("Wait 7 complete")); mre.WaitAsync().ContinueWith(t => CW("Wait 8 complete")); mre.WaitAsync().ContinueWith(t => CW("Wait 9 complete")); WaitUntilKey("set again"); mre.Set(); }
public void SubscriptionWithCancelledTaskCanBeDisposed() { var dr = new DefaultDependencyResolver(); using (var bus = new MessageBus(dr)) { var subscriber = new TestSubscriber(new[] { "key" }); var wh = new ManualResetEventSlim(); IDisposable subscription = bus.Subscribe(subscriber, null, async (result, state) => { if (result.Terminal) { return false; } await Task.Delay(50); var tcs = new TaskCompletionSource<bool>(); tcs.SetCanceled(); wh.Set(); return await tcs.Task; }, 10, null); bus.Publish("me", "key", "hello"); wh.Wait(); subscription.Dispose(); } }
/// <summary> /// Creates a new <see cref="MetadataRetriever"/> instance with the specified <paramref name="connectionString"/>. /// </summary> /// <param name="connectionString">GEP connection string for openHistorian.</param> private MetadataRetriever(string connectionString) { m_subscriber = new DataSubscriber { ConnectionString = connectionString, ReceiveInternalMetadata = true, ReceiveExternalMetadata = true }; m_subscriber.OperationalModes |= OperationalModes.UseCommonSerializationFormat | OperationalModes.CompressMetadata | OperationalModes.CompressSignalIndexCache; // Attach to needed subscriber events m_subscriber.ProcessException += m_subscriber_ProcessException; m_subscriber.ConnectionEstablished += m_subscriber_ConnectionEstablished; m_subscriber.MetaDataReceived += m_subscriber_MetaDataReceived; // Initialize the subscriber m_subscriber.Initialize(); // Create a wait handle to allow time to receive meta-data m_waitHandle = new ManualResetEventSlim(); // Start subscriber connection cycle m_subscriber.Start(); }
public void UseSqlNotificationsIfAvailable(bool supportSqlNotifications) { // Arrange var sqlDependencyAdded = false; var retryLoopCount = 0; var mre = new ManualResetEventSlim(); var dbProviderFactory = new MockDbProviderFactory(); var dbBehavior = new Mock<IDbBehavior>(); dbBehavior.Setup(db => db.UpdateLoopRetryDelays).Returns(_defaultRetryDelays); dbBehavior.Setup(db => db.StartSqlDependencyListener()).Returns(supportSqlNotifications); dbBehavior.Setup(db => db.AddSqlDependency(It.IsAny<IDbCommand>(), It.IsAny<Action<SqlNotificationEventArgs>>())) .Callback(() => { sqlDependencyAdded = true; mre.Set(); }); var operation = new ObservableDbOperation("test", "test", new TraceSource("test"), dbProviderFactory, dbBehavior.Object); operation.Faulted += _ => mre.Set(); operation.Queried += () => { retryLoopCount++; if (retryLoopCount > 1) { mre.Set(); } }; // Act ThreadPool.QueueUserWorkItem(_ => operation.ExecuteReaderWithUpdates((record, o) => { })); mre.Wait(); operation.Dispose(); // Assert Assert.Equal(supportSqlNotifications, sqlDependencyAdded); }
public void be_able_to_subscribe_to_empty_db() { using (var store = TestConnection.Create(_node.TcpEndPoint)) { store.ConnectAsync().Wait(); var appeared = new ManualResetEventSlim(false); var dropped = new CountdownEvent(1); var subscription = store.SubscribeToAllFrom(null, false, (_, x) => { if (!SystemStreams.IsSystemStream(x.OriginalEvent.EventStreamId)) appeared.Set(); }, _ => Log.Info("Live processing started."), (_, __, ___) => dropped.Signal()); Thread.Sleep(100); // give time for first pull phase store.SubscribeToAllAsync(false, (s, x) => { }, (s, r, e) => { }).Wait(); Thread.Sleep(100); Assert.IsFalse(appeared.Wait(0), "Some event appeared."); Assert.IsFalse(dropped.Wait(0), "Subscription was dropped prematurely."); subscription.Stop(Timeout); Assert.IsTrue(dropped.Wait(Timeout)); } }
public void When_command_committed_CompletionTaskSource_is_notified() { const int CommandCount = 5; var leader = CreateNetworkAndGetLeader(3); var commands = Builder<DictionaryCommand.Set>.CreateListOfSize(CommandCount) .All() .With(x => x.Completion = new TaskCompletionSource<object>()) .With(x => x.AssignedIndex = -1) .Build() .ToList(); var nonLeaderNode = Nodes.First(x => x.State != RaftEngineState.Leader); var commitsAppliedEvent = new ManualResetEventSlim(); nonLeaderNode.CommitIndexChanged += (oldIndex, newIndex) => { //CommandCount + 1 --> take into account NOP command that leader sends after election if (newIndex == CommandCount + 1) commitsAppliedEvent.Set(); }; commands.ForEach(leader.AppendCommand); Assert.True(commitsAppliedEvent.Wait(nonLeaderNode.Options.ElectionTimeout * 2)); commands.Should().OnlyContain(cmd => cmd.Completion.Task.Status == TaskStatus.RanToCompletion); }
public AsyncUpdateManager(Int32 processorAffinity) #endif { this.WorkerThread = new Thread(new ThreadStart(this.WorkerThread_Body)) { Name = "AsyncUpdateManager", IsBackground = true }; #if XBOX Check.ArgumentWithinRange("processortAffinity", processorAffinity, 3, 5); this.WorkerThread.SetProcessorAffinity(new Int32[] { processorAffinity }); #endif this.WorkAvailable = new ResetEvent(false); this.WorkDone = new ResetEvent(true); this.WorkQueue = new Queue <ParticleEffect>(); }
public void AutoResetEventFalseStopsFiringElapsed () { var elapsedCount = 0; var mre = new ST.ManualResetEventSlim (); timer = new Timer (50); timer.AutoReset = false; timer.Elapsed += (s, e) => { elapsedCount++; if (elapsedCount > 1) mre.Set (); }; timer.Start (); Assert.IsFalse (mre.Wait (1000), "#1 AutoReset=false didn't stop firing Elapsed, elapsedCount=" + elapsedCount); Assert.AreEqual (1, elapsedCount, "#2 wrong elapsedCount"); timer.Stop (); }
/// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(Boolean disposing) { if (disposing) { if (this.WorkAvailable != null) { this.WorkAvailable.Dispose(); this.WorkAvailable = null; } if (this.WorkDone != null) { this.WorkDone.Dispose(); this.WorkDone = null; } } }
public virtual bool TryGetResponse(out string response, int millisecondsTimeout) { var mre = new System.Threading.ManualResetEventSlim(false); string resp = response = null; ThreadPool.QueueUserWorkItem(_ => { resp = GetResponse(); mre.Set(); }); if (mre.Wait(millisecondsTimeout)) { response = resp; return(true); } else { return(false); } }
private static void ClientConnect() { using (var client = new AsyncSocketConnector()) using (var ready = new System.Threading.ManualResetEventSlim(false)) { client.FilterChain.AddLast("ssl", new SslFilter("TempCert", null)); client.FilterChain.AddLast("text", new ProtocolCodecFilter(new TextLineCodecFactory())); client.MessageReceived += (s, e) => { Debug.WriteLine("Client got: " + e.Message); ready.Set(); }; var session = client.Connect(new IPEndPoint(IPAddress.Loopback, port)).Await().Session; Debug.WriteLine("Client sending: hello"); session.Write("hello "); Debug.WriteLine("Client sending: send"); session.Write("send"); ready.Wait(3000); Assert.IsTrue(ready.IsSet); ready.Reset(); Assert.IsFalse(ready.IsSet); Debug.WriteLine("Client sending: hello"); session.Write(IoBuffer.Wrap(Encoding.UTF8.GetBytes("hello \n"))); Debug.WriteLine("Client sending: send"); session.Write(IoBuffer.Wrap(Encoding.UTF8.GetBytes("send\n"))); ready.Wait(3000); Assert.IsTrue(ready.IsSet); session.Close(true); } }
public override void Send(SendOrPostCallback d, object state) { if (Thread.CurrentThread != m_thread) { using (var signal = new System.Threading.ManualResetEventSlim()) { Post( (s) => { d(s); signal.Set(); }, state ); signal.Wait(); } } else { d(state); } }
internal void SleepWorkerThreadFunc(PriorityQueue <SleepItem> pendingSleeps, System.Threading.ManualResetEventSlim newSleepEvent) { while (true) { long now = TimeProvider.Ticks; SleepItem currentSleep; Monitor.Enter(pendingSleeps); if (pendingSleeps.Peek(out currentSleep)) { if (currentSleep.Tick(now)) { pendingSleeps.Dequeue(); Monitor.Exit(pendingSleeps); continue; } else { Monitor.Exit(pendingSleeps); } } else { Monitor.Exit(pendingSleeps); if (!newSleepEvent.Wait(SleepThreadTimeoutMs)) { return; } newSleepEvent.Reset(); continue; } long sleepUntil = currentSleep.Until; now = TimeProvider.Ticks; long timeToSleep = (sleepUntil - now) + SleepFudgeFactor; if (timeToSleep < SleepSpinThreshold) { int iteration = 1; while (TimeProvider.Ticks < sleepUntil) { Thread.SpinWait(20 * iteration); iteration += 1; } timeToSleep = 0; } if (timeToSleep > 0) { if (timeToSleep > MaximumSleepLength) { timeToSleep = MaximumSleepLength; } int msToSleep = 0; if (timeToSleep >= MinimumSleepLength) { msToSleep = (int)(timeToSleep / Time.MillisecondInTicks); } if (newSleepEvent != null) { newSleepEvent.Reset(); newSleepEvent.Wait(msToSleep); } } } }
/// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim" /> class. /// </summary> /// <param name="manualResetEvent">The manual reset event.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="manualResetEvent" /> /// is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> public ManualResetEventSlim(GlobalThreading.ManualResetEventSlim manualResetEvent) =>
/// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim" /> class. /// </summary> /// <param name="initialState">The initial signal state.</param> public ManualResetEventSlim(bool initialState) { internalResetEvent = new GlobalThreading.ManualResetEventSlim(initialState); eventLocal = true; }
void GatherNewEvents() { var log = Log.ScopeStart($"gathering new events"); long eventIdStart; using (var data = db.NewContext) eventIdStart = data.Events.OrderByDescending(e => e.TawId).Take(1).Select(e => e.TawId).FirstOrDefault(); // if (eventIdStart == default(long)) eventIdStart = 0; // 65000 is theoretically enough, it is about 1 year back, but sometimes we want more var doBreak = new System.Threading.ManualResetEventSlim(); var tasks = new List <Task>(); var pauseEachXEvents = 1; for (long i = 1; i < 100000; i++) { long eventId = eventIdStart + i; if (ShouldSkipEvent(eventId)) { continue; } // TODO: // a clever algorithm that works on ranges, e.g: try eventId+2 eventId+4 .. eventId+1024, // then eventId+1024-2 eventId+1024-4 eventId+1024-128 // find the next event that works by checking suitable ranges if (doBreak.IsSet) { break; } var task = Task.Run(async() => { if (doBreak.IsSet) { return; } var result = await dataParser.ParseEventData(log, eventId); if (result == WebDataParser.ParseEventResult.InvalidUriShouldRetry) { await Task.Delay(500); if (doBreak.IsSet) { return; } result = await dataParser.ParseEventData(log, eventId); if (result == WebDataParser.ParseEventResult.InvalidUriShouldRetry) { await Task.Delay(500); if (doBreak.IsSet) { return; } result = await dataParser.ParseEventData(log, eventId); if (result == WebDataParser.ParseEventResult.InvalidUriShouldRetry) { log.Warn("retried to parse event taw id:" + eventId + " already 3 times, failed all of them, probably last event, stopping event parsing"); doBreak.Set(); } } } else { if (pauseEachXEvents <= 100) { Interlocked.Increment(ref pauseEachXEvents); // successfull, lets parse more at the same time } } }); tasks.Add(task); if (i % pauseEachXEvents == 0) { tasks.WaitAll(Log); tasks.Clear(); } } tasks.WaitAll(Log); log.End(); }
/// <summary> /// Initializes a new instance of the <see cref="ManualResetEventSlim" /> class. /// </summary> public ManualResetEventSlim() { internalResetEvent = new GlobalThreading.ManualResetEventSlim(); eventLocal = true; }
/// <summary> /// Converts the source <see cref="GlobalThreading.ManualResetEventSlim" /> to a <see cref="ISetResetEvent" /> /// abstraction. /// </summary> /// <param name="source">The source event.</param> /// <returns>The abstracted version of the same event.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source" /> is <see langword="null" /> ( /// <see langword="Nothing" /> in Visual Basic). /// </exception> public static ISetResetEvent AsAbstraction(this GlobalThreading.ManualResetEventSlim source) => new ManualResetEventSlim( Requires.NotNull( source, nameof(source)));