public void PubSubTest() { UdpBus bus = (UdpBus)Reflector.GetField(this.pool, "bus"); object received = null; System.Threading.AutoResetEvent evt = new System.Threading.AutoResetEvent(false); this.pool.Start(); HostConfiguration hostSpec = new HostConfiguration(0){ CameraID = 2, Name = "mike", }; bus.Publish(Topics.HostReply, hostSpec, 3000); System.Threading.Thread.Sleep(6000); var host = this.pool[hostSpec.StationID]; Assert.IsNotNull(host); Assert.AreEqual("mike", host.Config.Name); hostSpec.Name = "jack"; bus.Publish(Topics.HostReply, hostSpec, 3000); System.Threading.Thread.Sleep(6000); host = this.pool[hostSpec.StationID]; Assert.AreEqual("jack", host.Config.Name); }
/// <summary> /// Starts monitoring the build queue for build jobs and blocks until the process is ended. /// </summary> public void Run() { var cancelTokenSource = new System.Threading.CancellationTokenSource(); var cancelToken = cancelTokenSource.Token; var buildReceivedEvent = new System.Threading.AutoResetEvent(false); this.Logger.LogInfoAsync("Build agent starting queue monitoring.").Wait(); // Queue monitoring thread var monitorTask = Task.Run(async() => { while (!cancelToken.IsCancellationRequested) { if (await this.WaitForJobsAsync()) { // Notify the main thread we have new builds. buildReceivedEvent.Set(); } } }, cancelToken); // Queue processing thread while (!cancelToken.IsCancellationRequested) { buildReceivedEvent.WaitOne(); this.Logger.LogInfoAsync("Processing new builds in queue...").Wait(); this.ProcessQueue(); } this.Logger.LogInfoAsync("Build agent is stopping.").Wait(); }
public void Finishing_the_initialisation_adds_the_release_archipelago_to_the_view() { // Given CreateMockFactory(); _mockPythonScriptRunner.Setup(m => m.Go()); var dummyConfiguration = new InformationRadiatorItemConfiguration(); var presenter = new GitVisualiserPresenter(dummyConfiguration); var wait = new System.Threading.AutoResetEvent(false); string nameOfIslandAddedToView = null; presenter.AddNewIslandToView += (sender, eventArgs) => { nameOfIslandAddedToView = eventArgs.Name; wait.Set(); }; presenter.DisplayTextualDataUpdate += (sender, eventArgs) => { }; // When var controlWidth = 100.0; var controlHeight = 200.0; presenter.FinishInitialisation(controlWidth, controlHeight); // Then Assert.IsTrue(wait.WaitOne(1000), "did not add island to view within 1 second"); Assert.AreEqual("Release Archipelago", nameOfIslandAddedToView); _mockPythonScriptRunner.VerifyAll(); }
private UUID ResolveIdFromName(string name) { UUID rid = UUID.Random(); UUID result = UUID.Zero; var waiter = new System.Threading.AutoResetEvent(false); EventHandler <AvatarPickerReplyEventArgs> handler = null; handler = delegate(object o, AvatarPickerReplyEventArgs a) { if (a.QueryID == rid) { client.Avatars.AvatarPickerReply -= handler; foreach (var i in a.Avatars) { UsernameToKeyCache[i.Value] = i.Key; KeyToUsernameCache[i.Key] = i.Value; } result = UsernameToKeyCache[name]; waiter.Set(); } }; client.Avatars.AvatarPickerReply += handler; client.Avatars.RequestAvatarNameSearch(name, rid); waiter.WaitOne(20000); client.Avatars.AvatarPickerReply -= handler; return(result); }
/// <summary> /// Invokes the GUI thread (blocking). The special feature is here that there is no deadlock even if another action executed in the Gui tasks waits for completion, supposed /// that it has used the <see cref="FromGuiThreadExecute"/> method. /// </summary> /// <param name="action">The action to be executed in the Gui thread.</param> public void InvokeGuiThread(Action action) { if (!_isInvokeRequiredForGuiThread()) { // no invoke required because we are already in the Gui thread action(); return; } System.Threading.AutoResetEvent myEvent = null; lock (_syncObject) { if (_invokerQueue.TryPeek(out var data)) { lock (data) { data.GuiAction = action; data.Event = (myEvent = new System.Threading.AutoResetEvent(false)); } } } if (null != myEvent) // we pushed the action to the stack, thus we now must wait for the event to be set after the action is executed { myEvent.WaitOne(); } else // TryPeek has returned no data, this we invoke directly { _invokeGuiThread(action); } }
/// </summary> /// <param name="rect"></param> internal void flushGraphics(Rectangle rect) { using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false)) { SilverlightImplementation.dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { IList <AsyncOp> tmp = renderingOperations; renderingOperations = pendingRenderingOperations; pendingRenderingOperations = tmp; if (rect == null) { _screen.Invalidate(); } else { _graphics.clip = rect; _graphics.destination.setClip(rect); _screen.Invalidate(); } _graphics.destination.setAlpha(255); _graphics.destination.setColor(0); are.Set(); }).AsTask().GetAwaiter().GetResult(); are.WaitOne(); } }
public void DeviceLocator_Notifications_DoesNotRaiseDeviceAvailableIfDisposed() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); DiscoveredSsdpDevice device = null; bool newlyDiscovered = false; var receivedNotification = false; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { device = args.DiscoveredDevice; newlyDiscovered = args.IsNewlyDiscovered; receivedNotification = true; }; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockAliveNotification()); server.Dispose(); eventSignal.WaitOne(1000); } Assert.IsFalse(receivedNotification); }
public void Fetching_new_messages_and_an_error_occurs() { // Given var target = TargetWithDefaultConfiguration(displayUpdatedInterval: 2, fetchUpdateInterval: 4); MessagesFromLeanKit("Hello", "World"); AttachTickerUpdate(target); // Force an update target.Update(); WaitForTickerUpdate(); var updateWait = new System.Threading.AutoResetEvent(false); mockTicker.Setup(m => m.GetMessages()) .Returns <List <string> >(null) .Callback(() => updateWait.Set()); // When for (int i = 0; i < 4; i++) { mockTimer.Raise(m => m.Tick += null, EventArgs.Empty); } updateWait.WaitOne(5000); // Then Assert.AreEqual("Error: Messages have not been downloaded", actualMessage); }
private string ResolveNameFromId(UUID key) { string result = key.ToString(); var waiter = new System.Threading.AutoResetEvent(false); EventHandler <UUIDNameReplyEventArgs> handler = null; handler = delegate(object o, UUIDNameReplyEventArgs a) { if (a.Names.ContainsKey(key)) { client.Avatars.UUIDNameReply -= handler; result = a.Names[key]; UsernameToKeyCache[result] = key; KeyToUsernameCache[key] = result; waiter.Set(); } }; client.Avatars.UUIDNameReply += handler; client.Avatars.RequestAvatarName(key); waiter.WaitOne(20000); client.Avatars.UUIDNameReply -= handler; return(result); }
public bool CapsQueueRunning() { if (Client.Network.CurrentSim.Caps.IsEventQueueRunning) return true; bool Success = false; // make sure caps event queue is running System.Threading.AutoResetEvent waitforCAPS = new System.Threading.AutoResetEvent(false); EventHandler<EventQueueRunningEventArgs> capsRunning = delegate(object sender, EventQueueRunningEventArgs e) { waitforCAPS.Set(); }; Client.Network.EventQueueRunning += capsRunning; if (waitforCAPS.WaitOne(10000, false)) { Success = true; } else { Success = false; Assert.Fail("Timeout waiting for event Queue to startup"); } Client.Network.EventQueueRunning -= capsRunning; return Success; }
static void Main(string[] args) { // args: // 0: jid, name // 1: passwd // 2: mcu jid // 3: cmd // 4: cmd_options if (args.Length == 5) { string xmpp_domain = Environment.GetEnvironmentVariable("xmpp_domain"); if (xmpp_domain == null) xmpp_domain = "app.zonekey.com.cn"; cs_zkrobot.client.NormalUser user = cs_zkrobot.client.UserFactory.makeNormal(); if (!user.login(args[0] + "@" + xmpp_domain, args[1])) { System.Console.WriteLine("login err: " + args[0] + "@" + xmpp_domain); } else { System.Console.WriteLine("req: to:" + args[2] + ", cmd=" + args[3] + ", options=" + args[4]); System.Threading.AutoResetEvent comp_evt = new System.Threading.AutoResetEvent(false); user.async_request(args[2] + "@" + xmpp_domain, args[3], args[4], cb_response, comp_evt); comp_evt.WaitOne(); user.logout(); } } }
/// <summary> /// Start to receive message /// </summary> public void Start() { lock (_sLockObj) { Id = _RecvId++; } lock (_LockObj) { if (!Started) { _CloseEvent = new System.Threading.ManualResetEvent(false); Closing = false; _Event = new System.Threading.AutoResetEvent(false); _Thread = new System.Threading.ProcessorThread(new System.Threading.ThreadStart(MessageProc)); _Thread.IsBackground = true; _Thread.SetProcessorAffinity(Id % Environment.ProcessorCount); _Thread.Start(); RestartTimes++; Started = true; } } }
private static FileStream tryGetFile(String fileName) { var autoResetEvent = new System.Threading.AutoResetEvent(false); while (true) { try { return(new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None)); } catch (IOException) { var fileSystemWatcher = new FileSystemWatcher(Path.GetDirectoryName(fileName)) { EnableRaisingEvents = true }; fileSystemWatcher.Changed += (o, e) => { if (Path.GetFullPath(e.FullPath) == fileName) { autoResetEvent.Set(); } }; autoResetEvent.WaitOne(); } } }
public void Test() { System.Threading.AutoResetEvent evt = new System.Threading.AutoResetEvent(false); Packets.LicensePlatePacket p = null; int count = 0; Manager mnger = new Manager(new PacketSplitter()); var parser = new Parsers.LicensePlateParser(); parser.Handler += licensePlate => { System.Diagnostics.Debug.WriteLine(licensePlate.LicensePlate.LicenseNumber); p = licensePlate; ++count; if (count > 1000) { evt.Set(); } }; mnger.Parsers.Add(parser); mnger.Start(); evt.WaitOne(10000); mnger.Stop(); Assert.IsNotNull(p); }
public void PubSubTest() { UdpBus bus = (UdpBus)Reflector.GetField(this.pool, "bus"); object received = null; System.Threading.AutoResetEvent evt = new System.Threading.AutoResetEvent(false); this.pool.Start(); HostConfiguration hostSpec = new HostConfiguration(0) { CameraID = 2, Name = "mike", }; bus.Publish(Topics.HostReply, hostSpec, 3000); System.Threading.Thread.Sleep(6000); var host = this.pool[hostSpec.StationID]; Assert.IsNotNull(host); Assert.AreEqual("mike", host.Config.Name); hostSpec.Name = "jack"; bus.Publish(Topics.HostReply, hostSpec, 3000); System.Threading.Thread.Sleep(6000); host = this.pool[hostSpec.StationID]; Assert.AreEqual("jack", host.Config.Name); }
protected override void OnShutdown() { if (base.IsInitialized) { System.Threading.AutoResetEvent wait = new System.Threading.AutoResetEvent(false); base.IOTaskPool.ExecuteInContext(delegate { Singleton <World> .Instance.Stop(true); Singleton <World> .Instance.Save(); wait.Set(); }); wait.WaitOne(); } IPCAccessor.Instance.Stop(); if (base.IOTaskPool != null) { base.IOTaskPool.Stop(false); } base.ClientManager.Pause(); BaseClient[] array = base.ClientManager.Clients.ToArray <BaseClient>(); for (int i = 0; i < array.Length; i++) { BaseClient baseClient = array[i]; baseClient.Disconnect(); } base.ClientManager.Close(); }
static void Main(string[] args) { var t2000 = new Timer(2000) { AutoReset = false }; var waitForTimeout = new System.Threading.AutoResetEvent(false); t2000.Elapsed += (s, e) => waitForTimeout.Set(); // stop 't2000' after one second, // and start it again, // we would expect our precision timer to run about 3 seconds now (1+2seconds) var t1000 = new Timer(1000) { AutoReset = false }; t1000.Elapsed += (s, e) => { t2000.Stop(); t2000.Start(); }; var precisionTimer = Stopwatch.StartNew(); precisionTimer.Start(); t2000.Start(); t1000.Start(); waitForTimeout.WaitOne(); precisionTimer.Stop(); Console.WriteLine($"Timeout after {precisionTimer.ElapsedMilliseconds}ms"); }
public void Should_be_able_to_configure_EasyNetQ_to_allow_message_with_a_blank_type_field() { var are = new System.Threading.AutoResetEvent(false); var validation = new NullMessageValidator(); var bus = RabbitHutch.CreateBus("host=localhost", r => r.Register<IMessageValidationStrategy>(x => validation)); bus.Subscribe<MyMessage>("null_validation_test", message => { Console.Out.WriteLine("Got message: {0}", message.Text); are.Set(); }); // now use the basic client API to publish some JSON to the message type exchange ... var factory = new RabbitMQ.Client.ConnectionFactory { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { const string exchange = "EasyNetQ_Tests_MyMessage:EasyNetQ_Tests"; const string routingKey = "#"; const string bodyString = "{ Text: \"Hello from Mr Raw :)\" }"; var body = System.Text.Encoding.UTF8.GetBytes(bodyString); var properties = channel.CreateBasicProperties(); channel.BasicPublish(exchange, routingKey, properties, body); } are.WaitOne(1000); }
public void Should_be_able_to_configure_EasyNetQ_to_allow_message_with_a_blank_type_field() { var are = new System.Threading.AutoResetEvent(false); var validation = new NullMessageValidator(); var bus = RabbitHutch.CreateBus("host=localhost", r => r.Register <IMessageValidationStrategy>(x => validation)); bus.Subscribe <MyMessage>("null_validation_test", message => { Console.Out.WriteLine("Got message: {0}", message.Text); are.Set(); }); // now use the basic client API to publish some JSON to the message type exchange ... var factory = new RabbitMQ.Client.ConnectionFactory { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { const string exchange = "EasyNetQ_Tests_MyMessage:EasyNetQ_Tests"; const string routingKey = "#"; const string bodyString = "{ Text: \"Hello from Mr Raw :)\" }"; var body = System.Text.Encoding.UTF8.GetBytes(bodyString); var properties = channel.CreateBasicProperties(); channel.BasicPublish(exchange, routingKey, properties, body); } are.WaitOne(1000); }
/// <summary> /// Release all resources (called by Dispose and Finalizer) /// </summary> private void FreeResources() { if (_timerDuration != null) { _timerDuration.Stop(); _timerDuration.Close(); _timerDuration.Dispose(); _timerDuration = null; } if (_timerSnapshot != null) { _timerSnapshot.Stop(); _timerSnapshot.Close(); _timerSnapshot.Dispose(); _timerSnapshot = null; } if (_waitEvent != null) { _waitEvent.Close(); _waitEvent = null; if (_frames != null) { foreach (Bitmap bitmap in _frames) { bitmap.Dispose(); } _frames.Clear(); _frames = null; } } }
/// <summary> /// This event fires when the process we have a reference to exits /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void AuxProcess_Exited(object sender, EventArgs e) { if (_aux.KeepAlive) { Log.Information(_aux.Name + " has stopped!"); //unsubscribe _auxProcess.Exited -= AuxProcess_Exited; End(); //restart as required if (!_stopping) { Log.Information("Re-starting " + _aux.Name); //wait some seconds first var autoEvent = new System.Threading.AutoResetEvent(false); var t = new System.Threading.Timer(_ => { ProcStart(); autoEvent.Set(); }, null, 5000, System.Threading.Timeout.Infinite); autoEvent.WaitOne(); t.Dispose(); } else { Log.Information(_aux.Name + " stopped"); Running = false; } } else { Log.Information(_aux.Name + " has completed"); //unsubscribe _auxProcess.Exited -= AuxProcess_Exited; _auxProcess.Dispose(); Running = false; } }
static void Main(string[] args) { var even = new System.Threading.AutoResetEvent(false); var process = new Process(); process.StartInfo.FileName = "tracert.exe"; process.StartInfo.Arguments = args[0]; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += (sender, e) => { if (!String.IsNullOrEmpty(e.Data)) { if (String.IsNullOrEmpty(Regex.Match(e.Data, "\\*").Value)) { var id = Regex.Match(e.Data, @"\b(\d+\s+)\b").Value; var ip = Regex.Match(e.Data, @"\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b").Value; if (!String.IsNullOrEmpty(ip) && !String.IsNullOrEmpty(id)) { var info = GetInfo(ip); Console.WriteLine($"ID: {int.Parse(id)} \tIP: {ip} \tAS: {info.Item1} \tCOUNTRY {info.Item2} \tDESCRIPTION: {info.Item3};"); } } else { even.Set(); } } }; process.Start(); process.BeginOutputReadLine(); even.WaitOne(); }
public static string downloadFile(this Uri uri, string targetFile) { if (uri.isNull()) { return(null); } "Downloading file {0} to location:{1}".info(uri.str(), targetFile); if (targetFile.fileExists()) // don't download if file already exists { "File already existed, so skipping download".debug(); return(targetFile); } var sync = new System.Threading.AutoResetEvent(false); var downloadControl = O2Gui.open <DownloadFile>("Downloading: {0}".format(uri.str()), 455, 170); downloadControl.setAutoCloseOnDownload(true); downloadControl.setCallBackWhenCompleted((file) => downloadControl.parentForm().close()); downloadControl.onClosed(() => sync.Set()); downloadControl.setDownloadDetails(uri.str(), targetFile); downloadControl.downloadFile(); sync.WaitOne(); // wait for download complete or form to be closed targetFile.file_WaitFor_CanOpen(); if (targetFile.fileExists()) { return(targetFile); } return(null); }
/// </summary> /// <param name="rect"></param> internal void flushGraphics(Rectangle rect) { using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false)) { SilverlightImplementation.dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { IList<AsyncOp> tmp = renderingOperations; renderingOperations = pendingRenderingOperations; pendingRenderingOperations = tmp; if (rect == null) { _screen.Invalidate(); } else { _graphics.clip = rect; _graphics.destination.setClip(rect); _screen.Invalidate(); } _graphics.destination.setAlpha(255); _graphics.destination.setColor(0); are.Set(); }).AsTask().GetAwaiter().GetResult(); are.WaitOne(); } }
public void RabbitMQ_deve_enviar_e_receber_mensagem() { var guid = Guid.NewGuid().ToString(); string queueName = $"fila-teste-rabbitmq-{guid}"; string message = $"Mensagem teste para RabbitMQ with guid {guid}"; var config = new FileMessagingConfig(LoadFileConfig(Broker.RabbitMQ)); using (var sender = new Messaging(config)) sender.EnqueueMessage(queueName, message); string received = ""; using (var receiver = new Messaging(config)) { System.Threading.AutoResetEvent waiter = new System.Threading.AutoResetEvent(false); receiver.StartListening(queueName, (args) => { received = args.AsString; waiter.Set(); return(true); }); waiter.WaitOne(); } Assert.AreEqual(message, received); }
private void GetControllerInput() { System.Threading.AutoResetEvent inputevent = new System.Threading.AutoResetEvent(false); inputDevice.SetNotification(inputevent); inputDevice.Acquire(); int pressed = -1; while (pressed == -1) { if (!inputevent.WaitOne(20000)) { break; } bool[] buttons = inputDevice.GetCurrentState().Buttons; for (int i = 0; i < buttons.Length; i++) { if (buttons[i]) { pressed = i; break; } } } inputDevice.Unacquire(); inputDevice.SetNotification(null); Invoke(new Action <int>(ButtonPressed), pressed); }
public void GetContinuousChanges() { System.Threading.AutoResetEvent evt = new System.Threading.AutoResetEvent(false); if (client.HasDatabase("test_changes")) { client.DeleteDatabase("test_changes"); } string id = null; var db = client.GetDatabase("test_changes"); using (CouchContinuousChanges ccc = db.GetCoutinuousChanges(new ChangeOptions() { Since = 0 }, (x, y) => { try { id = y.Id; Assert.IsNotNull(y.Id); Assert.IsTrue(y.Sequence > 0); } finally { evt.Set(); } }, new Result <CouchContinuousChanges>()).Wait()) { JDocument result = db.CreateDocument(new JDocument(), new Result <JDocument>()).Wait(); evt.WaitOne(); Assert.AreEqual(result.Id, id); } }
/// <summary> /// This event fires when the plex process we have a reference to exits /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Plex_Exited(object sender, EventArgs e) { OnPlexStatusChange(this, new StatusChangeEventArgs("Plex Media Server has stopped!")); //unsubscribe _plex.Exited -= Plex_Exited; //kill the supporting processes. KillSupportingProcesses(); if (_plex != null) { _plex.Dispose(); _plex = null; } //restart as required Settings settings = SettingsHandler.Load(); if (State != PlexState.Stopping && settings.AutoRestart) { OnPlexStatusChange(this, new StatusChangeEventArgs(string.Format("Waiting {0} seconds before re-starting the Plex process.", settings.RestartDelay))); State = PlexState.Pending; System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false); System.Threading.Timer t = new System.Threading.Timer((x) => { Start(); autoEvent.Set(); }, null, settings.RestartDelay * 1000, System.Threading.Timeout.Infinite); autoEvent.WaitOne(); t.Dispose(); } else { //set the status State = PlexState.Stopped; } }
public bool CapsQueueRunning() { if (Client.Network.CurrentSim.Caps.IsEventQueueRunning) { return(true); } bool Success = false; // make sure caps event queue is running System.Threading.AutoResetEvent waitforCAPS = new System.Threading.AutoResetEvent(false); NetworkManager.EventQueueRunningCallback capsRunning = delegate(Simulator sim) { waitforCAPS.Set(); }; Client.Network.OnEventQueueRunning += capsRunning; if (waitforCAPS.WaitOne(10000, false)) { Success = true; } else { Success = false; Assert.Fail("Timeout waiting for event Queue to startup"); } Client.Network.OnEventQueueRunning -= capsRunning; return(Success); }
public static void Run(string[] args) { if (args.Length == 0) { Command.Application application = new Command.Application(); IDisposable telnet = Parser.Listen(application, "telnet://:23"); IDisposable tcp = Parser.Listen(application, "tcp://:20"); IDisposable console = Parser.Listen(application, "console:///"); } else { Application application = new Application(); Settings.Module settings = new Settings.Module() { //Header = "<link href=\"resources/settings.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"resources/settings.css\" rel=\"stylesheet\" type=\"text/css\"/>", }; settings.Load("loader", new Loader(settings)); settings.Load("old.object", new Object()); settings.Load("application", new Command.Application()); application.Load(settings); application.Start(); System.Threading.AutoResetEvent wait = new System.Threading.AutoResetEvent(false); application.OnClosed += () => wait.Set(); wait.WaitOne(); //application.Execute(); } }
/// <summary> /// Shows the window. /// </summary> /// <param name="initializer">Action that will initialize <see cref="InteractiveWindow"/> before showing it.</param> public static void ShowWindow(Action <InteractiveWindow> initializer = null) { System.Threading.AutoResetEvent windowShown = new System.Threading.AutoResetEvent(false); ExecuteInSTA(() => { InteractiveWindow window = null; try { window = new InteractiveWindow(); initializer?.Invoke(window); window.Show(); windowShown.Set(); var _dispatcherFrame = new System.Windows.Threading.DispatcherFrame(); window.Closed += (obj, e) => { _dispatcherFrame.Continue = false; }; System.Windows.Threading.Dispatcher.PushFrame(_dispatcherFrame); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { windowShown.Set(); } window?.Close(); System.Windows.Threading.Dispatcher.CurrentDispatcher.InvokeShutdown(); }, waitForExecution: false); windowShown.WaitOne(); }
/// <summary> /// This event fires when the process we have a refrence to exits /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void auxProcess_Exited(object sender, EventArgs e) { if (_aux.KeepAlive) { OnStatusChange(this, new StatusChangeEventArgs(_aux.Name + " has stopped!")); //unsubscribe _auxProcess.Exited -= auxProcess_Exited; end(); //restart as required if (!_stopping) { OnStatusChange(this, new StatusChangeEventArgs("Re-starting " + _aux.Name)); //wait some seconds first System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false); System.Threading.Timer t = new System.Threading.Timer((x) => { start(); autoEvent.Set(); }, null, 5000, System.Threading.Timeout.Infinite); autoEvent.WaitOne(); t.Dispose(); } else { OnStatusChange(this, new StatusChangeEventArgs(_aux.Name + " stopped")); Running = false; } } else { OnStatusChange(this, new StatusChangeEventArgs(_aux.Name + " has completed")); //unsubscribe _auxProcess.Exited -= auxProcess_Exited; _auxProcess.Dispose(); Running = false; } }
public string MapGroup(UUID group) { if (GroupToIrcCache.ContainsKey(group)) { return(GroupToIrcCache[group]); } var result = group.ToString(); var waiter = new System.Threading.AutoResetEvent(false); EventHandler <GroupNamesEventArgs> handler = null; handler = delegate(object o, GroupNamesEventArgs a) { if (a.GroupNames.ContainsKey(group)) { client.Groups.GroupNamesReply -= handler; result = "#" + MakeIrcName(a.GroupNames[group]); GroupToIrcCache[group] = result; waiter.Set(); } }; client.Groups.GroupNamesReply += handler; client.Groups.RequestGroupName(group); waiter.WaitOne(20000); return(result); }
FacetedMesh MeshPrim(Primitive prim) { FacetedMesh mesh = null; if (prim.Sculpt == null || prim.Sculpt.SculptTexture == UUID.Zero) { mesh = Mesher.GenerateFacetedMesh(prim, DetailLevel.Highest); } else if (prim.Sculpt.Type != SculptType.Mesh) { Image img = null; if (LoadTexture(prim.Sculpt.SculptTexture, ref img, true)) { mesh = Mesher.GenerateFacetedSculptMesh(prim, (Bitmap)img, DetailLevel.Highest); } } else { var gotMesh = new System.Threading.AutoResetEvent(false); Client.Assets.RequestMesh(prim.Sculpt.SculptTexture, (success, meshAsset) => { if (!success || !FacetedMesh.TryDecodeFromAsset(prim, meshAsset, DetailLevel.Highest, out mesh)) { Logger.Log("Failed to fetch or decode the mesh asset", Helpers.LogLevel.Warning, Client); } gotMesh.Set(); }); gotMesh.WaitOne(20 * 1000, false); } return(mesh); }
private void _StartPingTask() { Console.WriteLine("_StartPingTask"); if (_pingThread != null) { return; } _pingARE = new System.Threading.AutoResetEvent(false); _pingThread = new System.Threading.Thread(() => { while (true) { try { var pingresult = Ruanal.Core.ApiSdk.SystemApi.MasterNodePing( diswork.ToList().Select(x => new int[] { x.TaskId, x.TaskVersion }).ToList() ); if (pingresult.code > 0 && pingresult.data.HasCmd > 0) { taskRouter.Router(); } } catch (Exception ex) { } _pingARE.WaitOne(TimeSpan.FromSeconds(_PingSeconds)); } }); _pingThread.IsBackground = true; _pingThread.Start(); }
public ServerLoopTimer(float period) { _timer = new Timer(period); _timer.Elapsed += () => { Set(); }; _are = new AutoResetEvent(true); _timer.Enabled = true; }
public HttpServerConnection(Uri server, string password, bool saltedpassword) { m_baseUri = server.ToString(); if (!m_baseUri.EndsWith("/")) { m_baseUri += "/"; } m_controlUri = new Uri(m_baseUri + CONTROL_SCRIPT); m_password = password; m_saltedpassword = saltedpassword; m_updateRequest = new Dictionary <string, string>(); m_updateRequest["action"] = "get-current-state"; m_updateRequest["longpoll"] = "false"; m_updateRequest["lasteventid"] = "0"; UpdateStatus(); //We do the first request without long poll, // and all the rest with longpoll m_updateRequest["longpoll"] = "true"; m_updateRequest["duration"] = "5m"; m_waitLock = new System.Threading.AutoResetEvent(false); m_requestThread = new System.Threading.Thread(ThreadRunner); m_pollThread = new System.Threading.Thread(LongPollRunner); m_requestThread.Name = "TrayIcon Request Thread"; m_pollThread.Name = "TrayIcon Longpoll Thread"; m_requestThread.Start(); m_pollThread.Start(); }
public ThreadProc(System.Threading.AutoResetEvent doneEvent, int StartRecord, int EndRecord) { this.doneEvent = doneEvent; this.StartRecord = StartRecord; this.EndRecord = EndRecord; this.EventFlag = false; }
public bool CapsQueueRunning() { if (Client.Network.CurrentSim.Caps.IsEventQueueRunning) { return(true); } bool Success = false; // make sure caps event queue is running System.Threading.AutoResetEvent waitforCAPS = new System.Threading.AutoResetEvent(false); EventHandler <EventQueueRunningEventArgs> capsRunning = delegate(object sender, EventQueueRunningEventArgs e) { waitforCAPS.Set(); }; Client.Network.EventQueueRunning += capsRunning; if (waitforCAPS.WaitOne(10000, false)) { Success = true; } else { Success = false; Assert.Fail("Timeout waiting for event Queue to startup"); } Client.Network.EventQueueRunning -= capsRunning; return(Success); }
/// <summary> /// Restart plex, wait for the specified delay between stop and start /// </summary> /// <param name="msDelay">The amount of time in ms to wait before starting after stop</param> internal void Restart(int delay) { Stop(); State = PlexState.Pending; System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false); System.Threading.Timer t = new System.Threading.Timer((x) => { Start(); autoEvent.Set(); }, null, delay, System.Threading.Timeout.Infinite); autoEvent.WaitOne(); t.Dispose(); }
public static PythonConsoleHost OpenPythonConsole(System.Windows.Forms.Form mainForm) { // ipy -D -X:TabCompletion -X:ColorfulConsole if (m_pythonConsoleHost == null) { m_pythonConsoleHost = new PythonConsoleHost(); //System.Threading.ManualResetEvent eve = new System.Threading.ManualResetEvent(false); dispatcher = mainForm; System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false); System.Threading.Thread _debugThread = new System.Threading.Thread(() => { int r = AllocConsole(); if (r == 0) { throw new InvalidOperationException("Can't AllocConsole!"); } StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput()); standardOutput.AutoFlush = true; Console.SetOut(standardOutput); //host.Options.RunAction = Microsoft.Scripting.Hosting.Shell.ConsoleHostOptions.Action.RunConsole; m_pythonConsoleHost.Run(new string[] { "-X:ColorfulConsole", "-X:Debug", "-X:TabCompletion", "-X:ExceptionDetail", "-X:ShowClrExceptions" }); // //are.Set(); m_pythonConsoleHost.Runtime.IO.RedirectToConsole(); IronPython.Runtime.ClrModule.SetCommandDispatcher(IronPython.Runtime.DefaultContext.Default, null); r = FreeConsole(); if (r == 0) { throw new InvalidOperationException("Can't FreeConsole!"); } m_pythonConsoleHost = null; }); _debugThread.IsBackground = true; _debugThread.SetApartmentState(System.Threading.ApartmentState.STA); _debugThread.Start(); // Don't establish the alternative input execution behavior until the other thread is ready. Note, 'are' starts out unsignalled. //are.WaitOne(); while (m_pythonConsoleHost.ScriptScope == null) { System.Threading.Thread.Sleep(1000); } IronPython.Runtime.ClrModule.SetCommandDispatcher(IronPython.Runtime.DefaultContext.Default, DispatchConsoleCommand); } return m_pythonConsoleHost; }
public void GivenIHaveAServer() { var wait = new System.Threading.AutoResetEvent(false); var server = ScenarioContext.Current.Get<System.ServiceModel.ServiceHost>(); server.Opened += (sender, args) => wait.Set(); server.Open(); Assert.IsTrue(wait.WaitOne(TimeSpan.FromSeconds(1))); }
public Control(string ServerAddress, int Port) { log = new Logger(AppInfo.Title + Port); m_sServerAddress = ServerAddress; m_iPort = Port; m_TCPClient = new System.Net.Sockets.TcpClient(); m_EventChannelConnectionComplete = new System.Threading.ManualResetEvent(false); m_sLastError = ""; m_EventReceivedFile = new System.Threading.AutoResetEvent(false); }
public Control(string ServerAddress, int Port, ref CarverLab.Utility.Logger logger) { log = logger; m_sServerAddress = ServerAddress; m_iPort = Port; m_TCPClient = new System.Net.Sockets.TcpClient(); m_EventChannelConnectionComplete = new System.Threading.ManualResetEvent(false); m_sLastError = ""; m_EventReceivedFile = new System.Threading.AutoResetEvent(false); }
// Sync up with the GLib thread. Should be called after the // name, role, or parent are changed in UiaAtkBridge when // checking for events, since we defer to an idle // handler to call atk to avoid deadlock when atk // emits signals. Called by RunInGuiThread in // UiaAtkBridge. public static void GlibSync () { System.Threading.AutoResetEvent sync = new System.Threading.AutoResetEvent (false); GLib.Timeout.Add (0, new GLib.TimeoutHandler (delegate { sync.Set (); return false; })); sync.WaitOne (); sync.Close (); }
/// <summary> /// Exectute the command /// </summary> /// <param name="args"></param> /// <param name="fromAgentID"></param> /// <returns></returns> public override string Execute(string[] args, UUID fromAgentID) { if (args.Length < 1) { return "Usage: viewnote [notecard asset uuid]"; } UUID note; if (!UUID.TryParse(args[0], out note)) { return "First argument expected agent UUID."; } System.Threading.AutoResetEvent waitEvent = new System.Threading.AutoResetEvent(false); System.Text.StringBuilder result = new System.Text.StringBuilder(); // define a delegate to handle the reply AssetManager.AssetReceivedCallback del = delegate(AssetDownload transfer, Asset asset) { if (transfer.Success) { result.AppendFormat("Raw Notecard Data: " + System.Environment.NewLine + " {0}", Utils.BytesToString(asset.AssetData)); waitEvent.Set(); } }; // verify asset is loaded in store if (Client.Inventory.Store.Contains(note)) { // retrieve asset from store InventoryItem ii = (InventoryItem)Client.Inventory.Store[note]; // subscribe to reply event Client.Assets.OnAssetReceived += del; // make request for asset Client.Assets.RequestInventoryAsset(ii, true); // wait for reply or timeout if (!waitEvent.WaitOne(10000, false)) { result.Append("Timeout waiting for notecard to download."); } // unsubscribe from reply event Client.Assets.OnAssetReceived -= del; } else { result.Append("Cannot find asset in inventory store, use 'i' to populate store"); } // return results return result.ToString(); }
public static Assembly compile(this string pathToFileToCompile, bool generateDebugSymbols) { PublicDI.CurrentScript = pathToFileToCompile; var csharpCompiler = new CSharp_FastCompiler(); csharpCompiler.generateDebugSymbols= generateDebugSymbols; var compileProcess = new System.Threading.AutoResetEvent(false); csharpCompiler.compileSourceCode(pathToFileToCompile.contents()); csharpCompiler.onCompileFail = () => compileProcess.Set(); csharpCompiler.onCompileOK = () => compileProcess.Set(); compileProcess.WaitOne(); return csharpCompiler.assembly(); }
public DebugProcess() { this.din = Console.In; this.dout = Console.Out; CmdSyncWait = new System.Threading.AutoResetEvent(false); imodules = new List<ICorDebugModule>(); iappdomains = new List<ICorDebugAppDomain>(); iassemblies = new List<ICorDebugAssembly>(); ibreakpoints = new List<ICorDebugFunctionBreakpoint>(); }
public Timer(System.Threading.TimerCallback callback) { if(!Node.MainNode.Ok()) { //this will also create the mainNode, if needed throw new Exception("Cannot use RosTimer without a working Node!"); } this.sig = new System.Threading.AutoResetEvent(false); this.callback = callback; this.running = true; this.paused = true; this.t = new System.Threading.Thread(new System.Threading.ThreadStart(this.Run)); this.t.Start(); }
public void GivenIHaveAClient(string endpoint) { var wait = new System.Threading.AutoResetEvent(false); var client = new Wcf.ServiceClient(endpoint); client.InnerChannel.Opened += (sender, args) => wait.Set(); client.Open(); Assert.IsTrue(wait.WaitOne(TimeSpan.FromSeconds(1))); ScenarioContext.Current.Set(client); }
public override string Execute(string[] args, UUID fromAgentID) { System.Threading.AutoResetEvent waitBalance = new System.Threading.AutoResetEvent(false); EventHandler<BalanceEventArgs> del = delegate(object sender, BalanceEventArgs e) { waitBalance.Set(); }; Client.Self.MoneyBalance += del; Client.Self.RequestBalance(); String result = "Timeout waiting for balance reply"; if (waitBalance.WaitOne(10000, false)) { result = Client.ToString() + " has L$: " + Client.Self.Balance; } Client.Self.MoneyBalance -= del; return result; }
public static Assembly compile_CodeSnippet(this string codeSnipptet, bool generateDebugSymbols) { //Note we can't use the precompiled engines here since there is an issue of the resolution of this code dependencies var csharpCompiler = new CSharp_FastCompiler(); csharpCompiler.generateDebugSymbols= generateDebugSymbols; var compileProcess = new System.Threading.AutoResetEvent(false); //csharpCompiler.compileSourceCode(pathToFileToCompile.contents()); csharpCompiler.compileSnippet(codeSnipptet); csharpCompiler.onCompileFail = () => compileProcess.Set(); csharpCompiler.onCompileOK = () => compileProcess.Set(); compileProcess.WaitOne(); var assembly = csharpCompiler.assembly(); return assembly; }
public override string Execute(string[] args, Guid fromAgentID) { System.Threading.AutoResetEvent waitBalance = new System.Threading.AutoResetEvent(false); AgentManager.BalanceCallback del = delegate(int balance) { waitBalance.Set(); }; Client.Self.OnBalanceUpdated += del; Client.Self.RequestBalance(); String result = "Timeout waiting for balance reply"; if (waitBalance.WaitOne(10000, false)) { result = Client.ToString() + " has L$: " + Client.Self.Balance; } Client.Self.OnBalanceUpdated -= del; return result; }
internal void flushGraphics(Rectangle rect) { //int counter = 0; //while (renderingOperations.Count() > 0) //{ // try // { // global::System.Threading.Tasks.Task.Run(() => global::System.Threading.Tasks.Task.Delay(global::System.TimeSpan.FromMilliseconds(5))).ConfigureAwait(false).GetAwaiter().GetResult(); // // don't let the EDT die here // counter++; // if (counter > 10) // { // Debug.WriteLine("Flush graphics timed out!!!"); // return; // } // } // catch (System.Exception e) // { // global::System.Diagnostics.Debug.WriteLine(e); // } //} using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false)) { SilverlightImplementation.dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { IList<AsyncOp> tmp = renderingOperations; renderingOperations = pendingRenderingOperations; pendingRenderingOperations = tmp; if (rect == null) { _screen.Invalidate(); } else { _graphics.clip = rect; _graphics.destination.setClip(rect); _screen.Invalidate(); } _graphics.destination.setAlpha(255); _graphics.destination.setColor(0); are.Set(); }).AsTask().GetAwaiter().GetResult(); are.WaitOne(); } }
public void NtpClient_DefaultServer_GetsNonNullResponse() { _GotResultSignal = new System.Threading.AutoResetEvent(false); var client = new Yort.Ntp.NtpClient(); try { client.TimeReceived += Client_TimeReceived; client.ErrorOccurred += Client_ErrorOccurred; client.BeginRequestTime(); _GotResultSignal.WaitOne(1000); Assert.AreNotEqual(null, _Result); } finally { client.TimeReceived -= this.Client_TimeReceived; client.ErrorOccurred -= this.Client_ErrorOccurred; } }
public void TestSendMessage() { var are = new System.Threading.AutoResetEvent(false); var connection = new SignalR.Client.Hubs.HubConnection("http://localhost:8081/"); var chatHub = connection.CreateProxy("chatHub_4"); connection.Start().ContinueWith(action => { if (action.IsFaulted) { Assert.Fail(string.Format("Error starting connection: {0}.", action.Exception.ToString())); } else Console.WriteLine("Connection started."); }).Wait(); bool addMessageExecuted = false; chatHub.On<WebApplication.ChatHub_4.MessageData>("AddMessage", (data) => { Assert.AreEqual("test name", data.UserName); Assert.AreEqual("hallo test world!", data.Message); addMessageExecuted = true; are.Set(); }); chatHub.Invoke("SendMessage", new { UserName = "******", Message = "hallo test world!" }).ContinueWith(task => { if (task.IsFaulted) Assert.Fail(string.Format("'SendMessage' invoke failed: {0}.", task.Exception.ToString())); else Console.WriteLine("'SendMessage' invoke completed."); }).Wait(); are.WaitOne(TimeSpan.FromSeconds(5)); Assert.IsTrue(addMessageExecuted); }
public static void DownloadDataInBackground(long blobID, string blobUrl) { System.Threading.AutoResetEvent waiter = new System.Threading.AutoResetEvent(false); BlobWebClient client = new BlobWebClient(); client.BlobID = blobID; client.BlobUrl = blobUrl; //client.BlobChecksum = blobChecksum; //client.BlobChecksumAlgorithm = blobChecksumAlgorithm; Uri uri = new Uri(blobUrl); client.DownloadDataCompleted += new System.Net.DownloadDataCompletedEventHandler(client_DownloadDataCompleted); client.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(client_DownloadProgressChanged); downloadClients.Add(blobID, client); client.DownloadDataAsync(uri, waiter); //waiter.WaitOne(); }
static void Main(string[] args) { TDInternalLogger.GetLogger().AddNewLogMessageEvent += new EventHandler<Eam.Client.Model.TechData.MyEventArgs.LogMessageEventArgs>(Program_AddNewLogMessageEvent); isStop = false; if (args.Length > 0) { xmlConfigurationFileName = args[0]; } System.Threading.Thread bufferUpdateMonitor = new System.Threading.Thread(UpdateMonitor); bufferUpdateMonitor.IsBackground = true; bufferUpdateMonitor.Start(); string input = Console.ReadLine(); while (input != "q") { input = Console.ReadLine(); } isStop = true; Console.WriteLine("Waiting for stop polling"); autoResetEvent = new System.Threading.AutoResetEvent(false); autoResetEvent.WaitOne(); }
/// <summary> /// Initializes a new instance of the <see cref="DebuggeeFlowController"/> class. /// </summary> /// <param name="client">The client.</param> public DebuggeeFlowController(IDebugClient client) { // Default is that we start in break mode. // TODO: Needs to be changed when we allow non intrusive attach/start for example. // DebugStatusGo = new System.Threading.AutoResetEvent(false); DebugStatusBreak = new System.Threading.AutoResetEvent(true); this.client = client; lock (eventCallbacksReady) { debuggerStateLoop = new System.Threading.Thread(() => DebuggerStateLoop()) { IsBackground = true }; debuggerStateLoop.SetApartmentState(System.Threading.ApartmentState.MTA); debuggerStateLoop.Start(); // Wait for loop thread to become ready. // System.Threading.Monitor.Wait(eventCallbacksReady); } }
public Connection(ref System.Net.Sockets.TcpClient TCPClient, System.Threading.ManualResetEvent eventChannelConnectionComplete, ref CarverLab.Utility.Logger logger) { log = logger; log.Context = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name; m_TCPClient = TCPClient; m_bConnected = false; m_iBufferMaxLength = 2048; m_iBufferLength = 0; m_bytesIncomingBuffer = new byte[m_iBufferMaxLength]; m_bDone = false; m_ThreadReceiveDataAndEnqueue = new System.Threading.Thread(new System.Threading.ThreadStart(this.ReceiveDataAndEnqueue)); m_ThreadAutomaticDequeue = new System.Threading.Thread(new System.Threading.ThreadStart(this.DequeCommands)); m_ThreadIsConnectionAlive = new System.Threading.Thread(new System.Threading.ThreadStart(this.IsConnectionAlive)); m_qCommands = System.Collections.Queue.Synchronized(new System.Collections.Queue()); m_EventChannelConnectionComplete = eventChannelConnectionComplete; m_EventChannelConnectionComplete.Reset(); m_EventMessageAvailable = new System.Threading.AutoResetEvent(false); m_EventThreadComplete = new System.Threading.ManualResetEvent(false); m_bIsRunning = false; m_bAutomaticDequeueingSuspended = false; m_EventAutomaticQueueing = new System.Threading.ManualResetEvent(true); }