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); }
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(); } }
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 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> /// 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(); }
static public void StartSearch() { // Additional properties we would like about the device. // Property strings are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/ff521659(v=vs.85).aspx string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable", "System.Devices.Aep.AepId", "System.Devices.Aep.Category" }; // BT_Code: Example showing paired and non-paired in a single query. string aqsAllBluetoothLEDevices = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")"; deviceWatcher = DeviceInformation.CreateWatcher( aqsAllBluetoothLEDevices, requestedProperties, DeviceInformationKind.AssociationEndpoint); // Register event handlers before starting the watcher. deviceWatcher.Added -= DeviceWatcher_Added; deviceWatcher.Updated -= DeviceWatcher_Updated; deviceWatcher.Removed -= DeviceWatcher_Removed; deviceWatcher.EnumerationCompleted -= DeviceWatcher_EnumerationCompleted; deviceWatcher.Stopped -= DeviceWatcher_Stopped; deviceWatcher.Added += DeviceWatcher_Added; deviceWatcher.Updated += DeviceWatcher_Updated; deviceWatcher.Removed += DeviceWatcher_Removed; deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted; deviceWatcher.Stopped += DeviceWatcher_Stopped; // Start the watcher. deviceWatcher.Start(); if (_searchMethod == 0) { _autoEvent.WaitOne(); } }
public String PostRequest(Iso8583Request req) { byte[] reqMsg = null; if (req.RequestString != null) { String sReq = req.RequestString.Trim(); if (String.IsNullOrEmpty(sReq)) { throw new HttpResponseException(HttpStatusCode.NoContent); } System.Text.RegularExpressions.Regex ws = new System.Text.RegularExpressions.Regex(@"\s+"); sReq = ws.Replace(sReq, ""); reqMsg = MessageUtility.StringToHex(sReq, true); if (reqMsg == null) { //throw new HttpResponseException(HttpStatusCode.InternalServerError); _outputData = "Error: Invalid request message string (not valid hexadecimal)"; } } try { MessageClient client = new MessageClient(req.ServerHost, req.ServerPort, null, this.PrintModel); client.IsSslEnabled = req.IsSSL; if (req.RequestString != null) { if (reqMsg != null) { client.SendBytes(reqMsg); } } else { client.Model = HttpContext.Current.Session != null ? HttpContext.Current.Session["model"] : null; if (client.Model != null) { _iso8583ResponseEvent.Reset(); client.SendModel(); _iso8583ResponseEvent.WaitOne(); } else { _outputData = "Error: Invalid request message (cannot be null value)"; } } } catch { //throw new HttpResponseException(HttpStatusCode.InternalServerError); _outputData = "Error: Cannot send request message to ISO 8583 server."; } if (_outputData.IndexOf("Error: ") == 0) { Logger.GetInstance().WriteLine(_outputData); } return(_outputData); }
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 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); }
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); }
/// </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 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); }
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); }
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); }
/// <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(); }
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); } }
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); }
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"); }
/// <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; } }
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(); }
/// <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; } }
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 bool Stop() { Trace.TraceInformation("Enter."); if (_thrServer == null) { Trace.TraceWarning("Server is already stopped."); return(false); } Trace.TraceInformation("Web Server thread state = " + _thrServer.ThreadState.ToString()); if (_thrServer.ThreadState != System.Threading.ThreadState.Stopped || _thrServer.ThreadState != System.Threading.ThreadState.StopRequested || _thrServer.ThreadState != System.Threading.ThreadState.Unstarted) { _thrServer.Abort(); Trace.TraceInformation("Abort was called on thread..."); _Abort.WaitOne(); Trace.TraceInformation("Thread has aborted."); _thrServer = null; return(true); } else { Trace.TraceWarning("Thread is in an unexpected state; abort cannot be called."); return(false); } }
private void AutoSaveData2XmlFuc() { while (AutoSaveData2XmlFuc_Running) { if (AutoSaveData2Xml_Flag) { try { SCADA.RFIDDATAT.DBWriteToXml(TaskDb, NCTaskXMLFileName); AutoSaveData2Xml_Flag = false; if (TaskDataForm.ctrlTaskData != null && TaskDataForm.ctrlTaskData.NCTaskMessageChangeHand != null) { TaskDataForm.ctrlTaskData.NCTaskMessageChangeHand.BeginInvoke(this, null, null, null); } System.Threading.Thread.Sleep(1000); } catch { } } else { SaveData2Xml_threaFucEvent.WaitOne(); } } }
private void backgroundWorkerMailing_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { if (this.backgroundWorkerMailing.CancellationPending) { e.Cancel = true; return; } // Seleccionamos emails validos EmailList = EmailList.Where(c => Utils.Validate.isEmail(c)).ToList(); // Ordenamos EmailList.Sort(delegate(String email1, String email2) { return(email1.CompareTo(email2)); }); string currentEmail; int total = EmailList.Count; int porcentaje = 0; List <string> emailsGroup = new List <string>(); for (int i = 0; i < total; i++) { if (this.backgroundWorkerMailing.CancellationPending == true) { e.Cancel = true; return; } currentEmail = EmailList[i]; porcentaje = (int)(((float)(i + 1) / (float)total) * 100); emailsGroup.Add(currentEmail); // Si tenemos un paquete completo o es el último email (y no se completa el paquete) if (emailsGroup.Count == Convert.ToInt32(this.textBoxMailingOffset.Text) || (i + 1) == total) { // send email pasandole el List emailsGroup try { this.SendEmail(emailsGroup); this.buildLogMsg(emailsGroup, i, "working"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Helper.ErrorFile(ex.ToString()); } finally { this.backgroundWorkerMailing.ReportProgress(porcentaje, emailsGroup[0] + " --> " + emailsGroup[emailsGroup.Count - 1]); emailsGroup.Clear(); // System.Threading.Thread.Sleep(Config.mailingWait * 1000); // No utilizamo sleep ya que entonces si pulsamos boton cancelar (his.backgroundWorkerMailing.CancelAsync()) // hay que esperar los Config.mailingWait * 1000 segundos hasta que se cancela el worker Ar.WaitOne(Config.mailingWait * 1000); } } } this.backgroundWorkerMailing.ReportProgress(100, ""); }
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 override string Execute(string[] args, UUID fromAgentID) { if (args.Length < 1) { return("Usage: key2name UUID"); } UUID key; if (!UUID.TryParse(args[0].Trim(), out key)) { return("UUID " + args[0].Trim() + " appears to be invalid"); } result.Remove(0, result.Length); waitQuery.Reset(); Client.Avatars.UUIDNameReply += Avatars_OnAvatarNames; Client.Groups.GroupProfile += Groups_OnGroupProfile; Client.Avatars.RequestAvatarName(key); Client.Groups.RequestGroupProfile(key); if (!waitQuery.WaitOne(10000, false)) { result.AppendLine("Timeout waiting for reply, this could mean the Key is not an avatar or a group"); } Client.Avatars.UUIDNameReply -= Avatars_OnAvatarNames; Client.Groups.GroupProfile -= Groups_OnGroupProfile; return(result.ToString()); }
/// <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; } }
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 static void CloneStringCrossThead_Thread() { try { while (true) { if (_CloneStringCrossThead_Event_Inner.WaitOne(1000) == false) { // 等了1秒没任务了,退出线程。 break; } if (_CloneStringCrossThead_CurrentValue != null) { _CloneStringCrossThead_CurrentValue = new string(_CloneStringCrossThead_CurrentValue.ToCharArray()); } _CloneStringCrossThead_Event.Set(); _CloneStringCrossThead_Event_Inner.Reset(); } } finally { _CloneStringCrossThead_Thread = null; _CloneStringCrossThead_Event.Reset(); _CloneStringCrossThead_Event_Inner.Reset(); } }
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(); } } }
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); }
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 string GetNextOutputLine(int millisecondsTimeout) { //Is output buffered? lock (m_lock) { if (m_stdOut.Count > 0) { return(m_stdOut.Dequeue()); } if (m_stdErr.Count > 0) { return(m_stdErr.Dequeue()); } } if (millisecondsTimeout > 0) { m_event.WaitOne(millisecondsTimeout); return(GetNextOutputLine(0)); } else { 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(); } }
// 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 (); }
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))); }
/// <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 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, 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; }
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, 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 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); }
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(); }
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; }
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 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; }
public void DeviceLocator_Notifications_StopListeningNoLongerReceivesNotifications() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); deviceLocator.StartListeningForNotifications(); deviceLocator.StopListeningForNotifications(); var receivedNotification = false; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { receivedNotification = true; eventSignal.Set(); }; server.MockReceiveBroadcast(GetMockAliveNotification()); eventSignal.WaitOne(1000); } Assert.IsFalse(receivedNotification); }
public void DeviceLocator_SearchAsync_ReturnsCachedDevices() { 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; eventSignal.Set(); }; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockAliveNotification()); eventSignal.WaitOne(10000); Assert.IsTrue(receivedNotification); var results = deviceLocator.SearchAsync(TimeSpan.Zero).GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.IsTrue(results.Any()); Assert.IsTrue(results.First().Usn == device.Usn); } }
public void DeviceLocator_SearchAsync_RaisesDeviceAvailableOnResponse() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var publishedDevice = CreateDeviceTree(); 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; eventSignal.Set(); }; var task = deviceLocator.SearchAsync(TimeSpan.FromSeconds(2)); server.MockReceiveMessage(GetMockSearchResponse(publishedDevice, publishedDevice.Udn)); eventSignal.WaitOne(10000); Assert.IsTrue(receivedNotification); var results = task.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.IsTrue(results.Any()); Assert.IsTrue(results.First().Usn == device.Usn); } }
public void DeviceLocator_SearchAsync_FiltersNotificationsDuringSearch() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var publishedDevice = CreateDeviceTree(); var publishedDevice2 = CreateDeviceTree(); deviceLocator.NotificationFilter = publishedDevice.Udn; deviceLocator.StartListeningForNotifications(); 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; eventSignal.Set(); }; var task = deviceLocator.SearchAsync(publishedDevice.Udn); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice2)); server.WaitForMessageToProcess(5000); eventSignal.Reset(); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice)); server.WaitForMessageToProcess(5000); eventSignal.WaitOne(10000); Assert.IsTrue(receivedNotification); var results = task.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.AreEqual(1, results.Count()); Assert.IsTrue(results.First().Usn == device.Usn); } }
public void DeviceLocator_Notifications_SubsequentNotificationsUpdatesSearchResults() { var publishedDevice = CreateDeviceTree(); var server = new MockCommsServer(); using (var deviceLocator = new MockDeviceLocator(server)) { var discoveredDevices = new List<DiscoveredSsdpDevice>(); using (var signal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { discoveredDevices.Add(args.DiscoveredDevice); signal.Set(); }; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice)); signal.WaitOne(10000); var updatedDevice = CreateDeviceTree(); updatedDevice.Uuid = publishedDevice.Uuid; updatedDevice.Location = new Uri("http://somewhereelse:1701"); updatedDevice.CacheLifetime = TimeSpan.FromDays(365); server.MockReceiveBroadcast(GetMockAliveNotification(updatedDevice)); signal.WaitOne(10000); } var first = discoveredDevices.First(); var second = discoveredDevices.Last(); Assert.IsTrue(discoveredDevices.Any()); Assert.AreNotEqual(first.DescriptionLocation, second.DescriptionLocation); Assert.AreNotEqual(first.CacheLifetime, second.CacheLifetime); Assert.AreEqual(second.CacheLifetime, TimeSpan.FromDays(365)); Assert.AreEqual(second.DescriptionLocation, new Uri("http://somewhereelse:1701")); } }
public void DeviceLocator_Notifications_SubsequentNotificationsUpdatesCachedDescriptionLocation() { var publishedDevice = CreateDeviceTree(); var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var discoveredDevices = new List<DiscoveredSsdpDevice>(); using (var signal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { discoveredDevices.Add(args.DiscoveredDevice); signal.Set(); }; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice)); signal.WaitOne(10000); var t = deviceLocator.SearchAsync(TimeSpan.FromSeconds(5)); var updatedDevice = CreateDeviceTree(); updatedDevice.Uuid = publishedDevice.Uuid; updatedDevice.Location = new Uri("http://somewhereelse:1701"); server.MockReceiveBroadcast(GetMockAliveNotification(updatedDevice)); signal.WaitOne(10000); var results = t.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.IsTrue(results.Any()); Assert.AreEqual(String.Format("{0}::{1}", publishedDevice.Udn, publishedDevice.FullDeviceType), discoveredDevices.Last().Usn); var first = discoveredDevices.First(); var second = discoveredDevices.Last(); Assert.AreNotEqual(first.DescriptionLocation, second.DescriptionLocation); Assert.AreEqual(second.DescriptionLocation, new Uri("http://somewhereelse:1701")); } }
public void Wait() { // // Push an event onto the wait queue. Eventually, a call to Notify or NotifyAll // will remove the event from the wait queue and signal it. // System.Threading.EventWaitHandle e = new System.Threading.AutoResetEvent(false); _waitQueue.AddLast(e); // // Preserve the lock count until we reaquire the lock. // int lockCount = _lockCount; _lockCount = 0; // // Fully release the lock. // for(int i = 0; i < lockCount; ++i) { _mutex.ReleaseMutex(); } // // Wait for the event to be set. // e.WaitOne(); // // Reacquire the lock the same number of times. // for(int i = 0; i < lockCount; ++i) { _mutex.WaitOne(); } _lockCount = lockCount; // // It is safe to close the event now because no other thread will use it (Notify // or NotifyAll has already removed the event from the wait queue). // e.Close(); }
public void DeviceLocator_Notifications_DoesNotRaiseDeviceAvailableWithUnmatchedNotificationFilter() { var publishedDevice = CreateDeviceTree(); var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var discoveredDevices = new List<DiscoveredSsdpDevice>(); using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { discoveredDevices.Add(args.DiscoveredDevice); eventSignal.Set(); }; deviceLocator.NotificationFilter = publishedDevice.Devices.First().Udn; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice)); eventSignal.WaitOne(1000); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice.Devices.First())); eventSignal.WaitOne(1000); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice.Devices.First().Devices.First())); eventSignal.WaitOne(1000); } Assert.IsTrue(discoveredDevices.Any()); Assert.IsFalse(discoveredDevices.Any((d) => { return !d.Usn.StartsWith(publishedDevice.Devices.First().Udn); })); }
public bool TimedWait(int timeout) { // // Push an event onto the wait queue. The event is removed from the queue if // Notify or NotifyAll is called, otherwise we have to remove it explicitly. // We use a LinkedListNode here because we can remove it in O(1) time. // System.Threading.EventWaitHandle e = new System.Threading.AutoResetEvent(false); LinkedListNode<System.Threading.EventWaitHandle> node = new LinkedListNode<System.Threading.EventWaitHandle>(e); _waitQueue.AddLast(node); // // Preserve the lock count until we reaquire the lock. // int lockCount = _lockCount; _lockCount = 0; // // Fully release the lock. // for(int i = 0; i < lockCount; ++i) { _mutex.ReleaseMutex(); } // // Wait for the event to be set or the timeout to expire. // bool b = e.WaitOne(timeout, false); // // NOTE: There's a race here if the timeout expired: another thread could // acquire the lock and call Notify. In turn, Notify could remove this event // from the wait queue and set it. Now we have a situation where the timeout // technically expired but the event was actually set. If we still treat this // as an expired timeout then the Notify will have been lost. // // The timeout isn't precise because we also have to wait an indeterminate // time to reacquire the lock. The simplest solution therefore is to check // the event one more time after acquiring the lock - if it's set now, we // act as if the wait succeeded. This might be an issue for a general-purpose // monitor implementation, but for Ice it shouldn't cause any problems. // // // Reacquire the lock the same number of times. // for(int i = 0; i < lockCount; ++i) { _mutex.WaitOne(); } _lockCount = lockCount; // // In the case of a timeout, check the event one more time to work around the // race condition described above. // if(!b) { b = e.WaitOne(0, false); } // // If our event was not signaled, we need to remove it from the wait queue. // if(!b) { Debug.Assert(node.List != null); // The node must still be in the wait queue. _waitQueue.Remove(node); } // // It is safe to close the event now because no other thread will use it. // e.Close(); return b; }
public void DeviceLocator_Notifications_SearchResponseUsesSharedMaxAge() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var publishedDevice = CreateDeviceTree(); publishedDevice.CacheLifetime = TimeSpan.FromMinutes(30); DiscoveredSsdpDevice device = null; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { device = args.DiscoveredDevice; eventSignal.Set(); }; var t = deviceLocator.SearchAsync(TimeSpan.FromSeconds(3)); System.Threading.Thread.Sleep(500); server.MockReceiveMessage(GetMockSearchResponseWithCustomCacheHeader(publishedDevice, publishedDevice.Udn, String.Format("CACHE-CONTROL: public, s-maxage={0}", publishedDevice.CacheLifetime.TotalSeconds))); eventSignal.WaitOne(10000); var results = t.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.IsTrue(results.Any()); Assert.AreEqual(device.CacheLifetime, results.First().CacheLifetime); } }