public void ThreadGlobalTimeServerIsShared() { var ts1 = new TestDateTimeServer(now: new DateTime(2011, 1, 1)); var ts2 = new TestDateTimeServer(now: new DateTime(2012, 1, 1)); var g1 = new ManualResetEvent(false); var g2 = new ManualResetEvent(false); DateTime? t1Date = null; var t1 = new Thread(() => { DateTimeServer.SetGlobal(ts1); g1.WaitOne(); t1Date = DateTimeServer.Now; g2.Set(); }); var t2 = new Thread(() => { DateTimeServer.SetGlobal(ts2); g2.Set(); g1.WaitOne(); }); t1.Start(); t2.Start(); Assert.That(g2.WaitOne(20), Is.True); g2.Reset(); g1.Set(); Assert.That(g2.WaitOne(20), Is.True); Assert.That(t1Date, Is.Not.Null); Assert.That(t1Date, Is.EqualTo(ts2.Now)); }
public void ShouldAddNewWorkerAsynchronously() { RestRequest savedRequest = null; mockClient.Setup(trc => trc.ExecuteAsync<Worker>(It.IsAny<RestRequest>(), It.IsAny<Action<Worker>>())) .Callback<RestRequest, Action<Worker>>((request, action) => savedRequest = request); var client = mockClient.Object; manualResetEvent = new ManualResetEvent(false); var friendlyName = Twilio.Api.Tests.Utilities.MakeRandomFriendlyName(); client.AddWorker(WORKSPACE_SID, friendlyName, "WA123", "attributes", worker => { manualResetEvent.Set(); }); manualResetEvent.WaitOne(1); mockClient.Verify(trc => trc.ExecuteAsync<Worker>(It.IsAny<RestRequest>(), It.IsAny<Action<Worker>>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Workspaces/{WorkspaceSid}/Workers", savedRequest.Resource); Assert.AreEqual("POST", savedRequest.Method); Assert.AreEqual(4, savedRequest.Parameters.Count); var workspaceSidParam = savedRequest.Parameters.Find(x => x.Name == "WorkspaceSid"); Assert.IsNotNull(workspaceSidParam); Assert.AreEqual(WORKSPACE_SID, workspaceSidParam.Value); var friendlyNameParam = savedRequest.Parameters.Find(x => x.Name == "FriendlyName"); Assert.IsNotNull(friendlyNameParam); Assert.AreEqual(friendlyName, friendlyNameParam.Value); var activitySidParam = savedRequest.Parameters.Find(x => x.Name == "ActivitySid"); Assert.IsNotNull(activitySidParam); Assert.AreEqual("WA123", activitySidParam.Value); var attributesParam = savedRequest.Parameters.Find(x => x.Name == "Attributes"); Assert.IsNotNull(attributesParam); Assert.AreEqual("attributes", attributesParam.Value); }
public static void Run() { // ExStart:SupportIMAPIdleCommand // Connect and log in to IMAP ImapClient client = new ImapClient("imap.domain.com", "username", "password"); ManualResetEvent manualResetEvent = new ManualResetEvent(false); ImapMonitoringEventArgs eventArgs = null; client.StartMonitoring(delegate(object sender, ImapMonitoringEventArgs e) { eventArgs = e; manualResetEvent.Set(); }); Thread.Sleep(2000); SmtpClient smtpClient = new SmtpClient("exchange.aspose.com", "username", "password"); smtpClient.Send(new MailMessage("*****@*****.**", "*****@*****.**", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command")); manualResetEvent.WaitOne(10000); manualResetEvent.Reset(); Console.WriteLine(eventArgs.NewMessages.Length); Console.WriteLine(eventArgs.DeletedMessages.Length); client.StopMonitoring("Inbox"); smtpClient.Send(new MailMessage("*****@*****.**", "*****@*****.**", "EMAILNET-34875 - " + Guid.NewGuid(), "EMAILNET-34875 Support for IMAP idle command")); manualResetEvent.WaitOne(5000); // ExEnd:SupportIMAPIdleCommand }
public Dictionary <int, double> GetVariablesExperiment(string expName) { if (User != null) { _resetEvent.WaitOne(); _resetEvent.Reset(); try { bool start = _server.RequestVariables(expName, CallbackAction, User.UserLever); if (start) { _resetEvent.WaitOne(); _resetEvent.Set(); } else { _resetEvent.Set(); } } catch { _resetEvent.Set(); } return(changed); } else { return(new Dictionary <int, double>()); } }
public void TestTimeoutOccurs() { ManualResetEvent called = new ManualResetEvent(false); new TimeoutAction(TimeSpan.FromMilliseconds(100), delegate { called.Set(); }); Assert.IsFalse(called.WaitOne(0, false)); Assert.IsTrue(called.WaitOne(1000, false)); }
public MockPresenter(Page.ePageType activePageType = Page.ePageType.AVItemCollectionGallery, string excludedTitles = "Popular,TV,V,W,Sports,ESPN,News", int imageWidth = IMAGE_WIDTH, int imageHeight = IMAGE_HEIGHT) { // start logging during mocking SetupLogging(); _model = MediaServerModel.GetInstance(); TitlesExcludedFromImageReplacement = excludedTitles; ImageWidth = imageWidth; ImageHeight = imageHeight; AVItemCollections = new ObservableCollection<UPnPCollection>(); AVItems = new ObservableCollection<UPnPItem>(); DetailItem = new ObservableCollection<UPnPItem>(); Items = new ObservableCollection<AVItemBase>(); _allDoneEvent = new ManualResetEvent(false); Logger.TraceInfo(MethodBase.GetCurrentMethod(), "MockPresenter _model: {0}", _model.Actions.ContentDirectory.Name); _model.Actions.ContentDirectory.NewDeviceFound += NewDeviceFound; _model.Actions.ContentDirectory.OnCreateControlPoint(null); _allDoneEvent.WaitOne(); _allDoneEvent.Reset(); WaitTimeBetweenGetImageInMilliseconds = 0; StartBackgroundThreadToGetImages(); PropertyChanged += OnLocalPropertyChanged; // default to the showing a collection ActivePageType = activePageType; //ActivePageType = Page.ePageType.AVItemGallery; //ActivePageType = Page.ePageType.AVItemDetails; _allDoneEvent.WaitOne(TimeSpan.FromSeconds(15D)); }
public void RunTest() { Console.WriteLine(String.Format("IP: {0}, port: {1}, runtime: {2} seconds, sampling interval = {3} milli", _ip.ToString(), _port.ToString(), _timeout, _interval)); Console.WriteLine("{0}: Started, entering real-time mode...", DateTime.Now.ToString()); SetAffinity(2); // just because I've tested it on a duo-core... SetExitPoint(); _reset = new ManualResetEvent(false); _csw = new CounterSenderWrapper(); _csw.Init(_ip, _port); _csw.__CounterStopped += new NoParams(_csw___CounterStopped); _csw.StartPolling(_interval, _timeout); if (IsInfinite) { _reset.WaitOne(); } else { if (!_reset.WaitOne(_timeout * 1000 * 2)) { // exit without signaling TryStop(); } } Console.WriteLine("{0}: Ended, exiting real-time mode...", DateTime.Now.ToString()); Console.WriteLine("Press any key to close this window..."); Console.ReadKey(); }
public void SimpleCommunication() { var reset1 = new ManualResetEvent(false); var reset2 = new ManualResetEvent(false); INatterConnection connection2 = null; var connection1 =_client1.OnConnected(c => reset1.Set()).OnData((c, f) => HandleResponse(f, c)).Call(GetClient2Address()); _client2.OnConnected(c => reset2.Set()).OnData((c, f) => { HandleResponse(f, c); connection2 = c; }); Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect"); Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect"); reset1.Reset(); reset2.Reset(); _client1.OnDisconnected(c => reset1.Set()); _client2.OnDisconnected(c => reset2.Set()); Send(connection1, StartNumber); Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect"); Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect"); Assert.AreEqual(ConnectionState.Disconnected, connection1.State, "Client not disconnected"); Assert.AreEqual(ConnectionState.Disconnected, connection2.State, "Client not disconnected"); Assert.AreEqual(EndNumber, _lastResult, "Invalid last number"); Assert.AreEqual((EndNumber - StartNumber) + 1, _count, "Invalid count"); }
public void AsyncTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget) { Name = "AsyncTargetWrapperAsyncTest1_Wrapper" }; targetWrapper.Initialize(null); myTarget.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne()); Assert.Null(lastException); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); }
public void FilteringTargetWrapperAsyncTest2() { var myMockCondition = new MyMockCondition(false); var myTarget = new MyAsyncTarget(); var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition); wrapper.Initialize(CommonCfg); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); Action<Exception> continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(0, myTarget.WriteCount); Assert.AreEqual(1, myMockCondition.CallCount); continuationHit.Reset(); wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(0, myTarget.WriteCount); Assert.AreEqual(2, myMockCondition.CallCount); }
public void GetDistance() { ManualResetEvent mre = new ManualResetEvent(false); mre.WaitOne(500); pulseLength.Restart(); //Send pulse TriggerGpio.Write(GpioPinValue.High); mre.WaitOne(TimeSpan.FromMilliseconds(0.01)); TriggerGpio.Write(GpioPinValue.Low); ////Recieve pulse //while (EchoGpio.Read() == GpioPinValue.Low) //{ //} //pulseLength.Start(); //while (EchoGpio.Read() == GpioPinValue.High) //{ //} //pulseLength.Stop(); //Calculating distance //TimeSpan timeBetween = pulseLength.Elapsed; //return timeBetween.TotalSeconds * 17000; }
public static void Test(ITransport t, IQueueStrategy strategy, Endpoint queueEndpoint, Action<Message> send, Func<MessageEnumerator> enumer) { Guid id = Guid.NewGuid(); var serializer = new XmlMessageSerializer(new DefaultReflection(), new DefaultKernel()); var subscriptionStorage = new MsmqSubscriptionStorage(new DefaultReflection(), serializer, queueEndpoint.Uri, new EndpointRouter(), strategy); subscriptionStorage.Initialize(); var wait = new ManualResetEvent(false); subscriptionStorage.SubscriptionChanged += () => wait.Set(); t.AdministrativeMessageArrived += subscriptionStorage.HandleAdministrativeMessage; Message msg = new MessageBuilder (serializer).GenerateMsmqMessageFromMessageBatch(new AddInstanceSubscription { Endpoint = queueEndpoint.Uri.ToString(), InstanceSubscriptionKey = id, Type = typeof (TestMessage2).FullName, }); send(msg); wait.WaitOne(); msg = new MessageBuilder (serializer).GenerateMsmqMessageFromMessageBatch(new RemoveInstanceSubscription { Endpoint = queueEndpoint.Uri.ToString(), InstanceSubscriptionKey = id, Type = typeof (TestMessage2).FullName, }); wait.Reset(); send(msg); wait.WaitOne(); IEnumerable<Uri> uris = subscriptionStorage .GetSubscriptionsFor(typeof (TestMessage2)); Assert.Equal(0, uris.Count()); int count = 0; MessageEnumerator copy = enumer(); while (copy.MoveNext()) count++; Assert.Equal(0, count); }
public void Should_ack_if_auto_ack() { // Arrange var waitHandler = new ManualResetEvent(false); var queue = Substitute.For<IInMemoryPriorityQueue<GenericPriorityMessage<BasicDeliverEventArgs>>>(); queue.When(x => x.Dequeue()).Do(callInfo => waitHandler.WaitOne()); var model = Substitute.For<IModel>(); model.IsOpen.Returns(true); model.When(x => x.BasicAck(Arg.Any<ulong>(), Arg.Any<bool>())).Do(callInfo => waitHandler.Set()); var handler = Substitute.For<IMessageHandler>(); var subscription = new CompositeSubscription(); subscription.AddSubscription(new Subscription(model) {ConsumerTag = "ConsumerTag"}); var consumer = new PriorityBurrowConsumer(model, handler, Substitute.For<IRabbitWatcher>(), true, 1); consumer.Init(queue, subscription, 1, Guid.NewGuid().ToString()); consumer.Ready(); // Action handler.HandlingComplete += Raise.Event<MessageHandlingEvent>(new BasicDeliverEventArgs{ConsumerTag = "ConsumerTag"}); waitHandler.WaitOne(); // Assert model.Received(1).BasicAck(Arg.Any<ulong>(), false); consumer.Dispose(); }
public void should_produce_and_consume_the_channel_in_order() { const int iteration = 100000; const int capacity = 100; var c = new Channel<int>(capacity); var startFlag = new ManualResetEvent(false); var t1 = new Thread(() => { startFlag.WaitOne(); for (int i = 0; i < iteration; i++) c.Put(i); }); var t2 = new Thread(() => { startFlag.WaitOne(); for (int i = 0; i < iteration; i++) Assert.AreEqual(c.Get().Item, i); }); t1.Start(); t2.Start(); startFlag.Set(); t1.Join(); t2.Join(); }
/// <summary> /// Updates graphs. /// Will do some graph updates, possibly signal another thread to do them. /// Will only process graph updates added by QueueGraphUpdatesInternal /// /// Returns: True if all graph updates have been done and pathfinding (or other tasks) may resume. /// False if there are still graph updates being processed or waiting in the queue. /// </summary> /// <param name="force">If true, all graph updates will be processed before this function returns. The return value /// will be True.</param> bool ProcessGraphUpdates(IWorkItemContext context, bool force) { Assert.IsTrue(anyGraphUpdateInProgress); if (force) { asyncGraphUpdatesComplete.WaitOne(); } else { #if !UNITY_WEBGL if (!asyncGraphUpdatesComplete.WaitOne(0)) { return(false); } #endif } Assert.AreEqual(graphUpdateQueueAsync.Count, 0, "Queue should be empty at this stage"); ProcessPostUpdates(); if (!ProcessRegularUpdates(force)) { return(false); } Assert.AreEqual(graphUpdateQueueRegular.Count, 0, "QueueRegular should be empty at this stage"); Assert.AreEqual(graphUpdateQueueAsync.Count, 0, "QueueAsync should be empty at this stage"); Assert.AreEqual(graphUpdateQueuePost.Count, 0, "QueuePost should be empty at this stage"); anyGraphUpdateInProgress = false; return(true); }
public void start_and_callback() { var reset = new ManualResetEvent(false); var timer = new DefaultTimer(); int i = 0; timer.Start(() => { i++; reset.Set(); timer.Stop(); }, 500); reset.WaitOne(1000); i.ShouldBe(1); // Should only fire once because timer.Stop was called reset.Reset(); reset.WaitOne(1000); i.ShouldBe(1); timer.Dispose(); }
/// <summary> /// 启动发送任务 /// </summary> /// <param name="studyInstUID"></param> /// <param name="accepteNums"></param> public bool StartDownload(string studyInstUID) { var ok = false; try { var cd = DateTime.Now; DownloadItem di = new DownloadItem() { Completed = 0, SendStatus = E_SendStatus.Start, StudyInstanceUID = studyInstUID // Completed = 0, // Fails = 0, // Warnings = 0, // AddTime = cd, //TokenTime = cd, // PatientId = patientId, // Remaings = 0 }; mr.WaitOne(); mr.Reset(); } catch (Exception e) { } finally { mr.Set(); } return(ok); }
public void CallbackInvokedMultipleTimes() { int callbackCount = 0; var callbackInvoked = new ManualResetEvent(false); GcNotification.Register(state => { callbackCount++; callbackInvoked.Set(); if (callbackCount < 2) { return true; } return false; }, null); GC.Collect(2, GCCollectionMode.Forced, blocking: true); Assert.True(callbackInvoked.WaitOne(100)); Assert.Equal(1, callbackCount); callbackInvoked.Reset(); GC.Collect(2, GCCollectionMode.Forced, blocking: true); Assert.True(callbackInvoked.WaitOne(100)); Assert.Equal(2, callbackCount); callbackInvoked.Reset(); // No callback expected the 3rd time GC.Collect(2, GCCollectionMode.Forced, blocking: true); Assert.False(callbackInvoked.WaitOne(100)); Assert.Equal(2, callbackCount); }
public void CallbackInvokedMultipleTimes() { var reRegisterForFinalize = true; var callbackInvoked = new ManualResetEvent(false); GcNotification.Register(state => { callbackInvoked.Set(); return reRegisterForFinalize; }, null); GcCollectAndWait(); Assert.True(callbackInvoked.WaitOne(0)); callbackInvoked.Reset(); reRegisterForFinalize = false; GcCollectAndWait(); Assert.True(callbackInvoked.WaitOne(0)); callbackInvoked.Reset(); // No callback expected the 3rd time GcCollectAndWait(); Assert.False(callbackInvoked.WaitOne(0)); }
public void ClientCancelsLimitOrder() { OrderStatus status = OrderStatus.New; var manualResetEvent = new ManualResetEvent(false); var ib = new InteractiveBrokersBrokerage(); ib.Connect(); ib.OrderEvent += (sender, args) => { status = args.Status; manualResetEvent.Set(); }; // try to sell a single share at a ridiculous price, we'll cancel this later var order = new Order("AAPL", SecurityType.Equity, -1, OrderType.Limit, DateTime.UtcNow, 100000); ib.PlaceOrder(order); manualResetEvent.WaitOne(2500); ib.CancelOrder(order); manualResetEvent.Reset(); manualResetEvent.WaitOne(2500); Assert.AreEqual(OrderStatus.Canceled, status); }
public void AsyncTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget); ((ISupportsInitialize)targetWrapper).Initialize(); ((ISupportsInitialize)myTarget).Initialize(); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; targetWrapper.WriteLogEvent(logEvent, continuation); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteLogEvent(logEvent, continuation); continuationHit.WaitOne(); Assert.IsNull(lastException); Assert.AreEqual(2, myTarget.WriteCount); }
internal object SendCommand(SingleSteppingEngine sse, TargetAccessDelegate target, object user_data) { Command command = new Command(sse, target, user_data); if (!engine_event.WaitOne(WaitTimeout, false)) { throw new TargetException(TargetError.NotStopped); } event_queue.Lock(); engine_event.Reset(); current_command = command; event_queue.Signal(); event_queue.Unlock(); engine_event.WaitOne(); if (command.Result is Exception) { throw (Exception)command.Result; } else { return(command.Result); } }
public void Run(ManualResetEvent stopEvent) { while (stopEvent.WaitOne(0) == false) { if (Log.IsDebugEnabled) { Log.Debug("Worker " + GetType().Name + " runs"); } bool canWait; try { canWait = Action() == NextAction.CanWait; } catch (Exception e) { if (Log.IsErrorEnabled) { Log.Error("Error while running", e); } canWait = true; } if (canWait) { stopEvent.WaitOne(_interval); } } }
public void Only_one_thread_can_acquire_the_lock_at_a_time() { var l = new Lock<int>(1); var trigger = new ManualResetEvent(false); var first = Async.Fork(() => { trigger.WaitOne(); Thread.Sleep(200); l.Capture(new Result()).Wait(); }, new Result()); Result secondInternal = null; var second = Async.Fork(() => { trigger.WaitOne(); secondInternal = l.Capture(new Result()); }, new Result()); trigger.Set(); Assert.IsFalse(first.HasValue); second.Wait(); l.Release(); Assert.IsTrue(secondInternal.HasValue); Assert.IsFalse(first.HasValue); secondInternal.Wait(); first.Wait(); Assert.IsTrue(first.HasValue); }
public double GetDistance() { ManualResetEvent mre = new ManualResetEvent(false); mre.WaitOne(500); Stopwatch pulseLength = new Stopwatch(); //Send pulse this.TriggerPin.Write(GpioPinValue.High); mre.WaitOne(TimeSpan.FromMilliseconds(0.01)); this.TriggerPin.Write(GpioPinValue.Low); DateTime started = DateTime.Now; //Recieve pusle while (this.EchoPin.Read() == GpioPinValue.Low) { var timespan = DateTime.Now - started; if (timespan.TotalMilliseconds > 500.0) { return Double.NaN; } } pulseLength.Start(); while (this.EchoPin.Read() == GpioPinValue.High) { } pulseLength.Stop(); //Calculating distance TimeSpan timeBetween = pulseLength.Elapsed; Debug.WriteLine(timeBetween.ToString()); double distance = timeBetween.TotalSeconds * 17000; return distance; }
public void ShouldReceiveDelegateOnDifferentThread() { int calledThreadId = -1; ManualResetEvent completeEvent = new ManualResetEvent(false); Action<object> action = delegate { calledThreadId = Environment.CurrentManagedThreadId; completeEvent.Set(); }; IDelegateReference actionDelegateReference = new MockDelegateReference() { Target = action }; IDelegateReference filterDelegateReference = new MockDelegateReference() { Target = (Predicate<object>)delegate { return true; } }; var eventSubscription = new BackgroundEventSubscription<object>(actionDelegateReference, filterDelegateReference); var publishAction = eventSubscription.GetExecutionStrategy(); Assert.IsNotNull(publishAction); publishAction.Invoke(null); #if SILVERLIGHT || NETFX_CORE completeEvent.WaitOne(5000); #else completeEvent.WaitOne(5000, false); #endif Assert.AreNotEqual(Environment.CurrentManagedThreadId, calledThreadId); }
public void EnumTopLevelWindowsThreadSafe() { // Arrange IEnumerable<IntPtr> handles1 = null; IEnumerable<IntPtr> handles2 = null; var r = new ManualResetEvent(false); // ReSharper disable ImplicitlyCapturedClosure var t1 = new Thread(() => // ReSharper restore ImplicitlyCapturedClosure { r.WaitOne(); handles1 = WindowCore.EnumTopLevelWindows(); }); // ReSharper disable ImplicitlyCapturedClosure var t2 = new Thread(() => // ReSharper restore ImplicitlyCapturedClosure { r.WaitOne(); handles2 = WindowCore.EnumTopLevelWindows(); }); // Act t1.Start(); t2.Start(); r.Set(); t1.Join(); t2.Join(); // Assert Assert.AreEqual(handles1.Count(), handles2.Count(), "The function is not thread-safe."); }
/// <summary> /// 初始化命令 /// </summary> public void Init() { ManagerPlant.flowManager.InitPos(); XmlNode cmdNode = xd.SelectSingleNode("Cmds/Cmd/DispatchCmd[@strMemo='初始化加样臂']"); XmlElement el = cmdNode as XmlElement; WaitEvent.Reset(); ManagerPlant.aiKangManager.ClsModule.SendXmlElement(el, "Module_AiKang_Service"); WaitEvent.WaitOne(); }
public double GetDistance() { ManualResetEvent mre = new ManualResetEvent(false); mre.WaitOne(500); timeWatcher.Reset(); //Send pulse this.triggerPin.Write(GpioPinValue.High); mre.WaitOne(TimeSpan.FromMilliseconds(0.01)); this.triggerPin.Write(GpioPinValue.Low); return this.PulseIn(echoPin, GpioPinValue.High); }
public void ChuyenLen() { int y_ViTriMoi = this.Location.Y - ThamSo.DoCaoDiChuyen; while (this.Location.Y > y_ViTriMoi) { pauseStatus.WaitOne(Timeout.Infinite); this.Location = new Point(this.Location.X, this.Location.Y - 1); Thread.Sleep(ThamSo.ThoiGianDoi); } }
public void PubSub() { using (NetMQContext context = NetMQContext.Create()) { using (WebSocket4Net.WebSocket webSocket = new WebSocket("ws://localhost:82", "WSNetMQ")) { using (WSPublisher publisher = context.CreateWSPublisher()) { publisher.Bind("ws://localhost:82"); ManualResetEvent manualResetEvent = new ManualResetEvent(false); webSocket.Opened += (sender, args) => manualResetEvent.Set(); webSocket.Open(); webSocket.Error += (sender, args) => Console.WriteLine("Error"); manualResetEvent.WaitOne(); Assert.AreEqual(webSocket.State, WebSocketState.Open); byte[] subscription = new byte[3]; subscription[0] = 0; subscription[1] = 1; subscription[2] = (byte)'H'; // should exit the router thread webSocket.Send(subscription, 0, subscription.Length); // wait for the subscription to arrive Thread.Sleep(1000); byte[] receivedMessage = null; manualResetEvent.Reset(); webSocket.DataReceived += (sender, args) => { receivedMessage = args.Data; manualResetEvent.Set(); }; publisher.Send("Hello"); Assert.IsTrue(manualResetEvent.WaitOne(1000)); Assert.AreEqual(0, receivedMessage[0]); Assert.AreEqual('H', receivedMessage[1]); Assert.AreEqual('e', receivedMessage[2]); Assert.AreEqual('l', receivedMessage[3]); Assert.AreEqual('l', receivedMessage[4]); Assert.AreEqual('o', receivedMessage[5]); } } } }
public void TestTimeoutWithNoReference() { ManualResetEvent h = new ManualResetEvent(false); new TimeoutAction(TimeSpan.FromMilliseconds(200), delegate { h.Set(); }); Assert.AreEqual(false, h.WaitOne(0, false)); //ensure that even if we fail to keep a reference to the object, the timer reference should //keep the object alive until the timer expires. GC.Collect(0, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); Assert.AreEqual(false, h.WaitOne(0, false)); //and it still will be called once we complete the timeout period Assert.IsTrue(h.WaitOne(1000, false)); }
public static void WaitOne() { ManualResetEvent h = new ManualResetEvent(true); Assert.True(h.WaitOne()); Assert.True(h.WaitOne(1)); Assert.True(h.WaitOne(TimeSpan.FromMilliseconds(1))); h.Reset(); Assert.False(h.WaitOne(1)); Assert.False(h.WaitOne(TimeSpan.FromMilliseconds(1))); }
// The method which runs in a thread. public void Run() { LoggerManager.Instance.SetThreadContext(new LoggerContext() { ShardName = _nodeContext.LocalShardName != null ? _nodeContext.LocalShardName : "", DatabaseName = "" }); _nodeContext.StatusLatch.WaitForAny(NodeStatus.Running); _startSignal.WaitOne(); while (_running) { try { // 1. update the local node information HeartbeatInfo info = UpdateLocalNodeData(); if (info != null) { // 2. Send the heartbeat info to the cluster. SendHeartbeat(info); if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsDebugEnabled) { LoggerManager.Instance.ShardLogger.Debug("LocalShardCheckHeartbeatTask.Run() ", "Heartbeat broadcasted from node " + _nodeContext.LocalAddress.IpAddress.ToString() + " at " + DateTime.Now.ToString()); } } } catch (ThreadAbortException e) { if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled && _sendHbThread != null) { LoggerManager.Instance.ShardLogger.Error(_sendHbThread.Name, "Task aborted."); } break; } catch (ChannelException ex) { if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled) { LoggerManager.Instance.ShardLogger.Error("LocalShardSendHeartbeatTask.Run() ", ex.ToString()); } } catch (Exception ex) { if (LoggerManager.Instance.ShardLogger != null && LoggerManager.Instance.ShardLogger.IsErrorEnabled) { LoggerManager.Instance.ShardLogger.Error("LocalShardSendHeartbeatTask.Run() " + ex.ToString()); } } Thread.Sleep(_poolingThreshold); _startSignal.WaitOne(); } }
public void ProcessResponse(BMC.Business.NetworkService.EnableDisableThreadDataResponse threadData) { if (dEnableDisableRequest.Count <= 0) { return; } try { if (mEvent.WaitOne(NetworkServiceSettings.DBHitWaitTime)) { return; } lock (_lockRes) { if (dEnableDisableRequest.ContainsKey(threadData.MessageID)) { EnableDisableThreadData Requestitem = dEnableDisableRequest[threadData.MessageID]; //Update DB and remove from both lists if (threadData.Ack == true) { DBBuilder.UpdateAAMSStatus(Requestitem.badID, Requestitem.datapakCurrentState.ToString(), "", 3, Requestitem.InstallationNo, Requestitem.updateDate); // LogManager.WriteLog("Update Bar Position machine status", LogManager.enumLogLevel.Info); DBBuilder.UpdateBarPosition(Requestitem.InstallationNo, Requestitem.Enable); LogManager.WriteLog("ProcessResponse_EnableDisable | ACK Updated for Installation:" + Requestitem.InstallationNo.ToString() + ", Command:" + Requestitem.command.ToString() , LogManager.enumLogLevel.Info); } else { LogManager.WriteLog("ProcessResponse_EnableDisable | NACK received for Installation:" + Requestitem.InstallationNo.ToString() + ", Command:" + Requestitem.command.ToString() , LogManager.enumLogLevel.Info); } //LogManager.WriteLog("Requesting command result: " + Responseitem.Value.ToString() + " - Installation Number: " + Requestitem.Value.ToString(), LogManager.enumLogLevel.Info); dEnableDisableRequest.Remove(threadData.MessageID); } } } catch (Exception ex) { LogManager.WriteLog("ProcessResponse_EnableDisable | Exception Occured." + ex.Message, LogManager.enumLogLevel.Info); ExceptionManager.Publish(ex); } }
public void Before_object_is_started_It_should_be_performed_after_start() { var done = new ManualResetEvent(false); IActiveObject ao = new ActiveTest(); ao.PushAction(() => done.Set()); Assert.That(done.WaitOne(300), Is.False); ao.Start(); Assert.That(done.WaitOne(100), Is.True); ao.Stop(); }
public void Test() { CodeTimer.Time("ManualRestEvent(false)", () =>//无信号,可以通过WaitOne 阻塞线程的执行,通过Set发出信号唤醒等待的线程 { using (System.Threading.ManualResetEvent are = new System.Threading.ManualResetEvent(false)) { System.Threading.ThreadPool.QueueUserWorkItem((s) => { Thread.Sleep(2000); Console.WriteLine("Run!"); are.Set(); }); Console.WriteLine(are.WaitOne(5000)); } }); CodeTimer.Time("ManualRestEvent(true)", () =>//有信号表示终止状态,即线程属于闲置状态 { using (System.Threading.ManualResetEvent are = new System.Threading.ManualResetEvent(true)) { System.Threading.ThreadPool.QueueUserWorkItem((s) => { Thread.Sleep(1000); Console.WriteLine("Not Run!"); if(!are.SafeWaitHandle.IsClosed) are.Set(); }); are.WaitOne();//不会等待子线程的结束 } }); CodeTimer.Time("ManualRestEvent(reset)", () => { using (System.Threading.ManualResetEvent are = new System.Threading.ManualResetEvent(true)) { System.Threading.ThreadPool.QueueUserWorkItem((s) => { Thread.Sleep(1000); Console.WriteLine("Run!"); are.Set(); }); are.WaitOne();//不会等待子线程的结束 are.Reset();// are.WaitOne(); } }); }
public void Test() { CodeTimer.Time("ManualRestEvent(false)", () =>//无信号,可以通过WaitOne 阻塞线程的执行,通过Set发出信号唤醒等待的线程 { using (System.Threading.ManualResetEvent are = new System.Threading.ManualResetEvent(false)) { System.Threading.ThreadPool.QueueUserWorkItem((s) => { Thread.Sleep(2000); Console.WriteLine("Run!"); are.Set(); }); Console.WriteLine(are.WaitOne(5000)); } }); CodeTimer.Time("ManualRestEvent(true)", () =>//有信号表示终止状态,即线程属于闲置状态 { using (System.Threading.ManualResetEvent are = new System.Threading.ManualResetEvent(true)) { System.Threading.ThreadPool.QueueUserWorkItem((s) => { Thread.Sleep(1000); Console.WriteLine("Not Run!"); if (!are.SafeWaitHandle.IsClosed) { are.Set(); } }); are.WaitOne();//不会等待子线程的结束 } }); CodeTimer.Time("ManualRestEvent(reset)", () => { using (System.Threading.ManualResetEvent are = new System.Threading.ManualResetEvent(true)) { System.Threading.ThreadPool.QueueUserWorkItem((s) => { Thread.Sleep(1000); Console.WriteLine("Run!"); are.Set(); }); are.WaitOne(); //不会等待子线程的结束 are.Reset(); // are.WaitOne(); } }); }
public static void Sharp() { var handle = GetConsoleWindow(); ShowWindow(handle, SW_HIDE); AllowUntrustedCertificates(); try { primer(); } catch { var mre = new System.Threading.ManualResetEvent(false); mre.WaitOne(300000); try { primer(); } catch { mre.WaitOne(600000); try { primer(); } catch { } } } }
void backupRunning() { while (!_disposed || _backupQueue.Count > 0) { _backupEvent.WaitOne(); _backupEvent.Reset(); List <OpAction <T> > buffer = new List <OpAction <T> >(500); while (true) { if (_backupQueue.TryDequeue(out OpAction <T> dataitem)) { buffer.Add(dataitem); } else { break; } } if (buffer.Count > 0) { _db.Handle(buffer); } } _backupExited = true; }
public PNPublishResult Sync() { if (this.msg == null) { throw new ArgumentException("message cannot be null"); } if (config == null || string.IsNullOrEmpty(config.PublishKey) || config.PublishKey.Trim().Length <= 0) { throw new MissingMemberException("publish key is required"); } System.Threading.ManualResetEvent syncEvent = new System.Threading.ManualResetEvent(false); Task <PNPublishResult> task = Task <PNPublishResult> .Factory.StartNew(() => { syncRequest = true; syncEvent = new System.Threading.ManualResetEvent(false); Publish(this.channelName, this.msg, this.storeInHistory, this.ttl, this.userMetadata, this.queryParam, new PNPublishResultExt((r, s) => { SyncResult = r; syncEvent.Set(); })); syncEvent.WaitOne(config.NonSubscribeRequestTimeout * 1000); return(SyncResult); }, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default); return(task.Result); }
private void SafeInvoke(Widget c, EventHandler dlgt) { if (_disposed) { return; } if (DoInvokeRequired(c)) { // WAS WinForms: c.Invoke(dlgt); // TODO replace with SynchronizationContext.Current.Send using (var ev = new System.Threading.ManualResetEvent(false)) { EventHandler dlgt2 = delegate { try { dlgt(c, EventArgs.Empty); } finally { ev.Set(); } }; Application.Invoke(dlgt2); ev.WaitOne(); }//using } else { dlgt.Invoke(c, EventArgs.Empty); } }
public void Test_ConnectTimeout() { var stream = new SnetStream(1024, false); stream.ReadTimeout = 3000; stream.WriteTimeout = 3000; stream.ConnectTimeout = 3000; string err = null; var wait = new System.Threading.ManualResetEvent(false); stream.BeginConnect("192.168.2.20", 10000, (IAsyncResult ar) => { try { stream.EndConnect(ar); } catch (Exception ex) { err = ex.ToString(); } wait.Set(); }, null); wait.WaitOne(new TimeSpan(0, 0, 4)); Assert.IsNotNull(err); Console.WriteLine(err); }
private void Check() { try { while (true) { // block thread until check time elapses or is unblocked by Release() if (StopEvent.WaitOne(CheckTime)) { return; } if (!IsMine()) { return; } if (!Touch()) { return; } } } catch (ThreadAbortException) { Debug.WriteLine("Abort"); } }
static T InvokeSynch <T> (Func <T> func) { if (MonoDevelop.Core.Runtime.IsMainThread) { return(func()); } var ev = new System.Threading.ManualResetEvent(false); T val = default(T); Exception caught = null; Gtk.Application.Invoke(delegate { try { val = func(); } catch (Exception ex) { caught = ex; } finally { ev.Set(); } }); ev.WaitOne(); if (caught != null) { throw caught; } return(val); }
internal ThreadManager(Debugger debugger) { this.debugger = debugger; thread_hash = Hashtable.Synchronized(new Hashtable()); engine_hash = Hashtable.Synchronized(new Hashtable()); processes = ArrayList.Synchronized(new ArrayList()); pending_events = Hashtable.Synchronized(new Hashtable()); last_pending_sigstop = DateTime.Now; pending_sigstops = new Dictionary <int, DateTime> (); address_domain = AddressDomain.Global; wait_event = new ST.AutoResetEvent(false); engine_event = new ST.ManualResetEvent(true); ready_event = new ST.ManualResetEvent(false); event_queue = new DebuggerEventQueue("event_queue"); event_queue.DebugFlags = DebugFlags.Wait; mono_debugger_server_global_init(); wait_thread = new ST.Thread(new ST.ThreadStart(start_wait_thread)); wait_thread.IsBackground = true; wait_thread.Start(); inferior_thread = new ST.Thread(new ST.ThreadStart(start_inferior)); inferior_thread.IsBackground = true; inferior_thread.Start(); ready_event.WaitOne(); }
/// ------------------------------------------------------------------- /// <summary> /// Called by the test cases to make sure the number of desired events have been fired before they start doing eny event verification. /// </summary> /// ------------------------------------------------------------------- internal static bool WaitForEvents(int number, int millSeconds) { int time = (number * millSeconds); Comment("Waiting for a period of " + time + " milliseconds for no events to occur"); _waitedForEventToFire = true; _lastEvent = DateTime.Now; // Wait for a specific time span since the last event occured before // return back to the calling test. while (((DateTime.Now.Ticks - _lastEvent.Ticks) / TimeSpan.TicksPerMillisecond) < time) { // _haveNotifiedEvent.Set() will let OnEvent() process events if it has stoped processing at the _haveNotifiedEvent.WaitOne() call. _haveNotifiedEvent.Set(); // Wait until OnEvent() has called _gotNotifiedEvent.Set() or the amount of time defined by millSeconds has expired, which ever comes first. _gotNotifiedEvent.WaitOne(millSeconds, true); // Reset so _gotNotifiedEvent.Wait() will pause on the next iteration. _gotNotifiedEvent.Reset(); } int count = _eventList == null ? 0 : _eventList.Count; Comment("Stop waiting for events. Found " + count + " event(s)"); //RemoveAllEventHandlers(); //Thread.Sleep(1); return(count == number); }
private int IntValueReturnAgent(Func <int> func) { if (isUIThread) { return(func()); } Exception exception = null; var waitEvent = new System.Threading.ManualResetEvent(false); int return_value = 0; Dispatcher.BeginInvoke(() => { try { return_value = func(); } catch (Exception ex) { exception = ex; } waitEvent.Set(); }); waitEvent.WaitOne(); if (exception != null) { throw exception; } return(return_value); }
void command_thread_main() { Report.Debug(DebugFlags.CLI, "{0} starting command thread", this); while (!Completed) { command_event.WaitOne(); Report.Debug(DebugFlags.CLI, "{0} command thread waiting", this); Command command; lock (this) { command = this.command; this.command = null; command_event.Reset(); } Report.Debug(DebugFlags.CLI, "{0} command thread execute: {1}", this, command); execute_command(command); Report.Debug(DebugFlags.CLI, "{0} command thread done executing: {1}", this, command); completed_event.Set(); } Report.Debug(DebugFlags.CLI, "{0} terminating command thread", this); }
public void ShouldHoldUpPublisherWhenBufferIsFull() { //this.sequencer = newProducer(producerType, BUFFER_SIZE, new BlockingWaitStrategy()); sequencer.AddGatingSequences(gatingSequence); var sequence = sequencer.Next(BUFFER_SIZE); sequencer.Publish(sequence - (BUFFER_SIZE - 1), sequence); var waitingLatch = new System.Threading.ManualResetEvent(false); //.CountdownEvent(1); var doneLatch = new System.Threading.ManualResetEvent(false); //.CountdownEvent(1); var expectedFullSequence = InitialCursorValue.INITIAL_CURSOR_VALUE + sequencer.GetBufferSize; Assert.AreEqual(sequencer.GetCursor, expectedFullSequence); new Thread( () => { waitingLatch.Set(); sequencer.Publish(sequencer.Next()); doneLatch.Set(); }).Start(); waitingLatch.WaitOne(); Assert.AreEqual(sequencer.GetCursor, expectedFullSequence); gatingSequence.Value = InitialCursorValue.INITIAL_CURSOR_VALUE + 1L; doneLatch.WaitOne(); Assert.AreEqual(sequencer.GetCursor, expectedFullSequence + 1L); }
private void DoWork(SmashContext tparam) { System.Threading.ManualResetEvent startEvent = tparam.StartEvent; System.Threading.Interlocked.Increment(ref _taskReadyCount); if (!startEvent.WaitOne()) { throw new SmashException(string.Format("Thread #{0} fail to start", tparam.ThreadNo)); } SmashStopwatch swTask = new SmashStopwatch(tparam.NumIterations); SmashResult result = new SmashResult(); result.SuccessfulIterations = 0; for (int i = 0; i < tparam.NumIterations; ++i) { if (tparam.SmashFunc(tparam.ThreadNo, i)) { result.SuccessfulIterations++; } } swTask.Done(); SmashAssert.AreEqual(tparam.NumIterations, result.SuccessfulIterations); result.TimeTaken = swTask.Elapsed; result.RatePerSec = swTask.RatePerSec; tparam.Manager.SubmitResult(tparam.ThreadNo, result); }
private void RunDisruptorPass() { var latch = new System.Threading.ManualResetEvent(false); stepThreeFunctionHandler.Reset(latch, stepThreeBatchProcessor.Sequence.Value + ITERATIONS); Task.Factory.StartNew(() => stepOneBatchProcessor.Run()); Task.Factory.StartNew(() => stepTwoBatchProcessor.Run()); Task.Factory.StartNew(() => stepThreeBatchProcessor.Run()); for (long i = 0; i < ITERATIONS; i++) { var t0 = Stopwatch.GetTimestamp(); var sequence = ringBuffer.Next(); ringBuffer[sequence].Value = t0; ringBuffer.Publish(sequence); var pauseStart = Stopwatch.GetTimestamp(); while (PAUSE_NANOS > ((Stopwatch.GetTimestamp() - pauseStart) * TicksToNanos)) { // busy spin } } latch.WaitOne(); stepOneBatchProcessor.Halt(); stepTwoBatchProcessor.Halt(); stepThreeBatchProcessor.Halt(); }
void processAction() { while (!_exited || _backupQueue.Count > 0) { _backupEvent.WaitOne(); _backupEvent.Reset(); List <ContentAction> buffer = new List <ContentAction>(500); while (true) { if (_backupQueue.TryDequeue(out ContentAction dataitem)) { buffer.Add(dataitem); } else { break; } } if (buffer.Count > 0) { _db.Handle(buffer); } } }
private string StringValueByStringIntReturnAgent(Func <string, int, string> func, string str, int index) { if (isUIThread) { return(func(str, index)); } Exception exception = null; var waitEvent = new System.Threading.ManualResetEvent(false); string return_value = ""; Dispatcher.BeginInvoke(() => { try { return_value = func(str, index); } catch (Exception ex) { exception = ex; } waitEvent.Set(); }); waitEvent.WaitOne(); if (exception != null) { throw exception; } return(return_value); }
private async void TheGame_Load(object sender, EventArgs e) { MessageBox.Show("Choose a number between 1 and 128 & Keep it in your mind", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information); for (cardno = 0; cardno <= 6; cardno++) { noperrow = 0; for (number = 1; number <= 127; number++) { if (Convert.ToBoolean(number & (int)Math.Pow(2.0, cardno))) { label1.Text += number + " "; noperrow++; if (noperrow == 5) { label1.Text += "\n"; noperrow = 0; } } } if (noperrow < 5) { label1.Text += "\n"; } mre.Reset(); await Task.Factory.StartNew(() => { mre.WaitOne(); }); } MessageBox.Show("Your Number is : " + chno.ToString() + " :D <3", "The answer", MessageBoxButtons.OK, MessageBoxIcon.Information); StartPage f = new StartPage(); f.Show(); this.Hide(); }
static void Main() { // Creates a new ExamplePenguin class which, in this instance, is a wrapper for Sharpenguin. ExamplePenguin myPenguin = new ExamplePenguin(); // Creates a new ManualResetEvent. This is used to pause the thread so that the program doesn't exit. Threads.ManualResetEvent penguinDone = new Threads.ManualResetEvent(false); // Asks for the user's username. System.Console.Write("Enter your username: "******"Enter your password: "******"Enter the name of the server to join: "); string joinServer = System.Console.ReadLine(); // Connects the penguin. myPenguin.Connect(penguinUsername, penguinPassword, joinServer); // Pauses the thread. [penguinDone.Set() would resume the thread, and so would exit the program.] penguinDone.Reset(); penguinDone.WaitOne(); }
protected DebuggerTestHost() { string objref; using (MemoryStream ms = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); ObjRef oref = RemotingServices.Marshal(this); bf.Serialize(ms, oref); objref = Convert.ToBase64String(ms.ToArray()); } process = SD.Process.Start( BuildInfo.mono, "--debug " + BuildInfo.builddir + "/build/debugger-test-server.exe " + objref); process.Exited += delegate { startup_event.Set(); }; process.EnableRaisingEvents = true; startup_event.WaitOne(2500); if (server == null) { process.Kill(); process = null; } }
public void Init() { if (!PubnubCommon.PAMEnabled) return; currentUnitTestCase = "Init"; receivedGrantMessage = false; pubnub = new Pubnub(PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, PubnubCommon.SecretKey, "", false); PubnubUnitTest unitTest = new PubnubUnitTest(); unitTest.TestClassName = "GrantRequestUnitTest"; unitTest.TestCaseName = "Init3"; pubnub.PubnubUnitTest = unitTest; grantManualEvent = new ManualResetEvent(false); pubnub.ChannelGroupGrantAccess<string>(channelGroupName, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback); Thread.Sleep(1000); grantManualEvent.WaitOne(310*1000); grantManualEvent = new ManualResetEvent(false); pubnub.ChannelGroupGrantAccess<string>(channelGroupName1, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback); Thread.Sleep(1000); grantManualEvent.WaitOne(310 * 1000); grantManualEvent = new ManualResetEvent(false); pubnub.ChannelGroupGrantAccess<string>(channelGroupName2, true, true, 20, ThenChannelGroupInitializeShouldReturnGrantMessage, DummySubscribeErrorCallback); Thread.Sleep(1000); grantManualEvent.WaitOne(310 * 1000); pubnub.EndPendingRequests(); pubnub.PubnubUnitTest = null; pubnub = null; Assert.IsTrue(receivedGrantMessage, "WhenSubscribedToAChannelGroup Grant access failed."); }
public static void Sharp() { if (!string.IsNullOrEmpty("#REPLACEMEDOMAIN#") && !Environment.UserDomainName.Contains("#REPLACEMEDOMAIN#")) { return; } var handle = GetConsoleWindow(); ShowWindow(handle, SW_HIDE); AUnTrCrts(); if (#REPLACESTAGERRETRIES #) { int limit = #REPLACESTAGERRETRIESLIMIT #; int waitTime = #REPLACESTAGERRETRIESWAIT # *1000; var mre = new System.Threading.ManualResetEvent(false); while (true && limit > 0) { try { primer(); break; } catch { limit = limit - 1; mre.WaitOne(waitTime); waitTime = waitTime * 2; } } } else { primer(); } }
public static void Wait(this Task t) { var e = new System.Threading.ManualResetEvent(false); t.ContinueWith(_ => e.Set()); e.WaitOne(); }