public void ThreadGlobalTimeServerIsShared() { var ts1 = new TestDateTimeServer(now: new DateTime(2011, 1, 1)); var ts2 = new TestDateTimeServer(now: new DateTime(2012, 1, 1)); var g1 = new ManualResetEvent(false); var g2 = new ManualResetEvent(false); DateTime? t1Date = null; var t1 = new Thread(() => { DateTimeServer.SetGlobal(ts1); g1.WaitOne(); t1Date = DateTimeServer.Now; g2.Set(); }); var t2 = new Thread(() => { DateTimeServer.SetGlobal(ts2); g2.Set(); g1.WaitOne(); }); t1.Start(); t2.Start(); Assert.That(g2.WaitOne(20), Is.True); g2.Reset(); g1.Set(); Assert.That(g2.WaitOne(20), Is.True); Assert.That(t1Date, Is.Not.Null); Assert.That(t1Date, Is.EqualTo(ts2.Now)); }
public void AcceptAsyncShouldUseAcceptSocketFromEventArgs() { var readyEvent = new ManualResetEvent(false); var mainEvent = new ManualResetEvent(false); var listenSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var serverSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Socket acceptedSocket = null; Exception ex = null; ThreadPool.QueueUserWorkItem(_ => { SocketAsyncEventArgs asyncEventArgs; try { listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listenSocket.Listen(1); asyncEventArgs = new SocketAsyncEventArgs {AcceptSocket = serverSocket}; asyncEventArgs.Completed += (s, e) => { acceptedSocket = e.AcceptSocket; mainEvent.Set(); }; } catch (Exception e) { ex = e; return; } finally { readyEvent.Set(); } try { if (listenSocket.AcceptAsync(asyncEventArgs)) return; acceptedSocket = asyncEventArgs.AcceptSocket; mainEvent.Set(); } catch (Exception e) { ex = e; } }); Assert.IsTrue(readyEvent.WaitOne(1500)); if (ex != null) throw ex; var clientSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(listenSocket.LocalEndPoint); clientSocket.NoDelay = true; Assert.IsTrue(mainEvent.WaitOne(1500)); Assert.AreEqual(serverSocket, acceptedSocket, "x"); mainEvent.Reset(); if (acceptedSocket != null) acceptedSocket.Close(); listenSocket.Close(); readyEvent.Close(); mainEvent.Close(); }
/// <summary> /// Downloads the resource as a string from the URI specified. /// </summary> /// <param name="address">The URI represented by the Uri object, from which to download data.</param> /// <returns></returns> public string DownloadData(Uri address) { var initRequest = (HttpWebRequest)WebRequest.Create(address); var result = String.Empty; var responseComplete = new ManualResetEvent(false); if (Headers != null) initRequest.Headers = Headers; initRequest.BeginGetResponse(ar => { var signaled = false; try { var response = GetResponse(ar); result = ReadResponseToString(response); responseComplete.Set(); signaled = true; } catch (Exception) { if (!signaled) { responseComplete.Set(); } } }, initRequest); return result; }
public void SimpleCommunication() { var reset1 = new ManualResetEvent(false); var reset2 = new ManualResetEvent(false); INatterConnection connection2 = null; var connection1 =_client1.OnConnected(c => reset1.Set()).OnData((c, f) => HandleResponse(f, c)).Call(GetClient2Address()); _client2.OnConnected(c => reset2.Set()).OnData((c, f) => { HandleResponse(f, c); connection2 = c; }); Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect"); Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(5)), "Failed to connect"); reset1.Reset(); reset2.Reset(); _client1.OnDisconnected(c => reset1.Set()); _client2.OnDisconnected(c => reset2.Set()); Send(connection1, StartNumber); Assert.IsTrue(reset1.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect"); Assert.IsTrue(reset2.WaitOne(TimeSpan.FromSeconds(80)), "Failed to disconnect"); Assert.AreEqual(ConnectionState.Disconnected, connection1.State, "Client not disconnected"); Assert.AreEqual(ConnectionState.Disconnected, connection2.State, "Client not disconnected"); Assert.AreEqual(EndNumber, _lastResult, "Invalid last number"); Assert.AreEqual((EndNumber - StartNumber) + 1, _count, "Invalid count"); }
public WebBrowser(Arguments args) : this() { var address = args["address"].Value as string; DispatcherThread.StartNew(() => { //TODO: Add ability to define browser settings. if (address != null) m_webBrowser = new ChromiumWebBrowser(address); else m_webBrowser = new ChromiumWebBrowser(""); }).Wait(); //Ensure that the web browser is initialized. using (var evt = new ManualResetEvent(false)) { m_webBrowser.BrowserInitialized += (o, e) => evt.Set(); DispatcherThread.StartNew(() => { if (m_webBrowser.IsBrowserInitialized) { evt.Set(); } }); evt.WaitOne(); } }
public void IterateErrorHandlingTest() { var xs = Enumerable.Range(0, 10).Select(x => Observable.Return(new Data(x))); int errors = 0; Func<IObservable<Data>> createOriginSource = () => TpObservableExtensions.Iterate(xs, x => { if (x.Body != 5) { Console.WriteLine("Handler: " + x.Body); } else { throw new ApplicationException(); } }, Scheduler.ThreadPool, s => Console.WriteLine("Trace: " + s)); var ev = new ManualResetEvent(false); var source = TpObservableExtensions.ToSelfRepairingHotObservable(createOriginSource, _ => { }, e => { Console.WriteLine(e); errors++; if (errors == 5) { ev.Set(); } }); using (source.Subscribe(x => Console.WriteLine("Observer: " + x.Body), Console.WriteLine, () => { ev.Set(); Console.WriteLine("Observer: completed"); })) { ev.WaitOne(TimeSpan.FromSeconds(5)).Should(Be.True); } }
public void GetConfig_CanLoadConfigsFromMultipleThreads() { const string configKey = "MyCustomConfig"; var configLoader = new FakeLoader(false, true); var configRepository = new ConfigRepository(configLoader); const int maxThreads = 10; Exception ex = null; IConfig config = null; var getConfigCompletedEvent = new ManualResetEvent(false); for(int i = 0; i < maxThreads; i++) { int remainingThreads = i; ThreadPool.QueueUserWorkItem(s => { try { config = configRepository.GetConfig(configKey, false); if(Interlocked.Decrement(ref remainingThreads) == 0) { getConfigCompletedEvent.Set(); } } catch(Exception innerEx) { getConfigCompletedEvent.Set(); ex = innerEx; throw; } }); } getConfigCompletedEvent.WaitOne(); getConfigCompletedEvent.Close(); Assert.IsNotNull(config); Assert.IsNull(ex); }
public void Loaders_are_thread_safe() { kernel.Register(Component.For<SlowLoader>()); var @event = new ManualResetEvent(false); int[] count = {10}; Exception exception = null; for (int i = 0; i < count[0]; i++) { ThreadPool.QueueUserWorkItem(o => { try { kernel.Resolve<Implementation>("not registered"); if (Interlocked.Decrement(ref count[0]) == 0) { @event.Set(); } } catch (Exception e) { exception = e; // this is required because NUnit does not consider it a failure when // an exception is thrown on a non-main thread and therfore it waits. @event.Set(); } } ); } @event.WaitOne(); Assert.IsNull(exception); Assert.AreEqual(0, count[0]); }
/// <summary> /// Marks message as deleted. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception> /// <exception cref="POP3_ClientException">Is raised when POP3 serveer returns error.</exception> public void MarkForDeletion() { if(this.IsDisposed){ throw new ObjectDisposedException(this.GetType().Name); } if(this.IsMarkedForDeletion){ return; } using(MarkForDeletionAsyncOP op = new MarkForDeletionAsyncOP()){ using(ManualResetEvent wait = new ManualResetEvent(false)){ op.CompletedAsync += delegate(object s1,EventArgs<MarkForDeletionAsyncOP> e1){ wait.Set(); }; if(!this.MarkForDeletionAsync(op)){ wait.Set(); } wait.WaitOne(); wait.Close(); if(op.Error != null){ throw op.Error; } } } }
public void TestPolling() { var reddit = new RedditClient(() => new HttpClient()); var pollingClient = new RedditPollingClient(reddit, "funny", TimeSpan.FromSeconds(10), ex => { }); var resetEvent = new ManualResetEvent(false); var subscription = pollingClient.Posts.Subscribe( x => Debug.WriteLine($"New post: {x.Title}"), ex => { Debug.WriteLine($"Error while retrieving reddit posts: {ex.Message}"); resetEvent.Set(); }, () => { Debug.WriteLine("Finished retrieving posts"); resetEvent.Set(); }); pollingClient.Start(); resetEvent.WaitOne(60000); }
public void NatsClient_PubSub_Queue() { string recvMsg = null; int counter = 0; using (var nats1 = new NatsClient(NatsUrl)) using (var nats2 = new NatsClient(NatsUrl)) using (var waitHandle = new ManualResetEvent(false)) { nats1.Connect(); nats1.Subscribe("test", new Options("queue"), (msg, source) => { Console.WriteLine("Received: {0}", msg); recvMsg = msg; counter += 1; waitHandle.Set(); }); nats2.Connect(); nats2.Subscribe("test", new Options("queue"), (msg, source) => { Console.WriteLine("Received: {0}", msg); recvMsg = msg; counter += 1; waitHandle.Set(); }); nats2.Publish("test", "Hello"); waitHandle.WaitOne(1000); } Assert.AreEqual("Hello", recvMsg); Assert.AreEqual(1, counter); }
public void CloseTest() { int shutdownCount = 0; int closeCount = 0; ManualResetEvent resetEvent = new ManualResetEvent(false); NetworkConnection connection = new NetworkConnection(_client); connection.Shutdown += (sender, args) => { shutdownCount++; resetEvent.Set(); }; connection.ConnectionClosed += (sender, args) => { closeCount++; resetEvent.Set(); }; connection.Start(); connection.Close(); Assert.That(resetEvent.WaitOne(2000)); Assert.That(shutdownCount, Is.EqualTo(0)); Assert.That(closeCount, Is.EqualTo(1)); }
/// <summary> /// Executes a specified method and waits until the action is completed /// </summary> /// <param name="action">The action.</param> public static void ExecuteActionAndWait(Action<IAsyncContinuation> action) { var waitHandle = new ManualResetEvent(false); Exception exception = null; var continuation = AsyncHelpers.CreateContinuation( () => waitHandle.Set(), exc => { exception = exc; waitHandle.Set(); }); // try it synchronously, otherwise wait action(continuation); bool signalOccurred = WaitHandle.WaitAll(new WaitHandle[] { waitHandle }, MaxMillisecondsTimeout); if (!signalOccurred) { throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "The action has not completed within {0} milliseconds", MaxMillisecondsTimeout)); } if (exception != null) { // wrap the exception to preserve the original call-stack throw new TaupoInfrastructureException("An exception occurred during asynchronous execution", exception); } }
public static void ExecuteSync(string key, string command, Action<Action<object>, Action<Exception, object>> action) { var resetEvent = new ManualResetEvent(initialState: false); Exception exception = null; action( //delegate to invoke on success s => resetEvent.Set(), //delegate to invoke on test error (e, s) => { exception = e; resetEvent.Set(); }); var timeout = KetchupConfig.Current.SyncCommandTimeout; if (!resetEvent.WaitOne(timeout * 1000)) throw new TimeoutException( string.Format( "Command timed out on before async response was returned.\nCommand: {0}\nKey: {1}", command, key )); if (exception != null) throw exception; }
/// <summary> /// Get the OAuth tokens required to access the cloud based API (Synchronous) /// </summary> /// <param name="code">The code received after the user has given the application permission to access their company files</param> /// <returns>The tokens that are required to access the user's company files</returns> public OAuthTokens GetTokens(string code) { var wait = new ManualResetEvent(false); OAuthTokens oauthTokens = null; Exception ex = null; var requestUri = default(Uri); GetTokens(code, (statusCode, tokens) => { oauthTokens = tokens; wait.Set(); }, (uri, exception) => { requestUri = uri; ex = exception; wait.Set(); }); if (wait.WaitOne(new TimeSpan(0, 0, 0, 60))) { ex.ProcessException(requestUri); } return oauthTokens; }
/// <summary> /// Does all the magic of spinning up the bot. /// </summary> private static void Main() { _logger.Info("Starting console runner"); try { // We may actually not log to the console past this point, so let's go ahead and spam something // here just in case. Console.WriteLine("We've spun up the bot and are currently logging to our appenders. Hit CTL+C to quit."); // We want to know when it's ok to shutdown the bot. using (var shutdownManualResetEvent = new ManualResetEvent(false)) { // Get our application context from Spring.NET. var applicationContext = ContextRegistry.GetContext(); // Grab our bean and spin it up. var bot = applicationContext.GetObject("SpikeLite") as SpikeLite; // Listen for status changes so we know when to exit bot.BotStatusChanged += (sender, eventArgs) => { if (eventArgs.NewStatus == BotStatus.Stopped) { _logger.Info("Bot status set to stopped, shutting down."); shutdownManualResetEvent.Set(); } }; // This won't actually work while we're debugging: // http://connect.microsoft.com/VisualStudio/feedback/details/524889/debugging-c-console-application-that-handles-console-cancelkeypress-is-broken-in-net-4-0 // Handle SIGTERM gracefully. Console.CancelKeyPress += ((sender, args) => { _logger.Info("Cancel key pressed. Shutting down bot."); args.Cancel = true; // Clean up. bot.Shutdown("Caught SIGTERM, quitting"); // Signal that we're ready to shutdown the bot. shutdownManualResetEvent.Set(); }); bot.Start(); // Wait untill we're ready to shutdown the bot. shutdownManualResetEvent.WaitOne(); _logger.Info("Application shutting down."); applicationContext.Dispose(); } } catch (Exception ex) { _logger.ErrorFormat("Fatal error attempting to start the bot: {0} - {1}", ex.Message, ex.StackTrace); } }
public ManualResetEvent CreateEventSignal() { ManualResetEvent signal = new ManualResetEvent(false); this.Monitor.DeviceChanged += (sender, e) => signal.Set(); this.Monitor.DeviceConnected += (sender, e) => signal.Set(); this.Monitor.DeviceDisconnected += (sender, e) => signal.Set(); return signal; }
public static IObservable<Socket> ToConnectObservable(this IPEndPoint endpoint, Selector selector, CancellationToken token) { return Observable.Create<Socket>(observer => { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { Blocking = false }; Exception error = null; bool isConnected = false; try { socket.Connect(endpoint); isConnected = true; } catch (Exception exception) { if (!exception.IsWouldBlock()) error = exception; } if (!isConnected && error == null) { var waitEvent = new ManualResetEvent(false); var waitHandles = new[] {token.WaitHandle, waitEvent}; selector.AddCallback(SelectMode.SelectWrite, socket, _ => { try { if (!socket.Connected) socket.Connect(endpoint); selector.RemoveCallback(SelectMode.SelectWrite, socket); isConnected = true; waitEvent.Set(); } catch (Exception exception) { if (exception.IsWouldBlock()) return; error = exception; waitEvent.Set(); } }); if (WaitHandle.WaitAny(waitHandles) == 0) token.ThrowIfCancellationRequested(); } if (error == null) observer.OnNext(socket); else observer.OnError(error); observer.OnCompleted(); return Disposable.Empty; }); }
public static IDictionary<String, Object> Invoke(Activity activity, IDictionary<String, Object> inputParameters = null, object[] extensions = null) { if (inputParameters == null) { inputParameters = new Dictionary<String, Object>(); } WorkflowApplication application = new WorkflowApplication(activity, inputParameters); if (extensions != null) { foreach (var ext in extensions) { application.Extensions.Add(ext); } } Exception thrownException = null; IDictionary<String, Object> outputParameters = new Dictionary<String, Object>(); ManualResetEvent waitHandle = new ManualResetEvent(false); application.OnUnhandledException = (WorkflowApplicationUnhandledExceptionEventArgs arg) => { // Preserve the stack trace in this exception // This is a hack into the Exception.InternalPreserveStackTrace method that allows us to re-throw and preserve the call stack _preserveStackTraceMethod.Invoke(arg.UnhandledException, null); thrownException = arg.UnhandledException; return UnhandledExceptionAction.Terminate; }; application.Completed = (WorkflowApplicationCompletedEventArgs obj) => { waitHandle.Set(); outputParameters = obj.Outputs; }; application.Aborted = (WorkflowApplicationAbortedEventArgs obj) => waitHandle.Set(); application.Idle = (WorkflowApplicationIdleEventArgs obj) => waitHandle.Set(); application.PersistableIdle = (WorkflowApplicationIdleEventArgs arg) => { waitHandle.Set(); return PersistableIdleAction.Persist; }; application.Unloaded = (WorkflowApplicationEventArgs obj) => waitHandle.Set(); application.Run(); waitHandle.WaitOne(); if (thrownException != null) { throw thrownException; } return outputParameters; }
/// <summary>Execute the process and return its exitcode</summary> public override int Execute(Process proc, Encoding encoding) { var cancel = new ManualResetEvent(false); var buffer = new byte[256]; var stdin = Console.OpenStandardInput(); var result = stdin.BeginRead(buffer, 0, buffer.Length, ar => cancel.Set(), null); proc.StartInfo.RedirectStandardInput = true; proc.EnableRaisingEvents = true; proc.Exited += (sender, args) => cancel.Set(); int code = -1; do { var start = DateTime.Now; code = Run(proc, encoding, () => { cancel.Reset(); proc.StandardInput.Close(); cancel.WaitOne(); if (result.IsCompleted) { Console.WriteLine("==> Shut down"); stdin.EndRead(result); proc.Kill(); return 0; } else { proc.WaitForExit(); return proc.ExitCode; } }); var elapsed = DateTime.Now - start; if (code > 0) { if (elapsed.Seconds < WAIT_FOR_STARTUP) { Console.WriteLine(); Console.WriteLine("*** Process exited right after being started, aborting"); stdin.Close(); return code; } else { Console.WriteLine(); Console.WriteLine("*** Process exited with exitcode {0}, respawning...", code); Thread.Sleep(WAIT_BEFORE_RESPAWN * 1000); } } } while (code > 0); // Either via user-interactive shutdown or via runtime exiting itself stdin.Close(); return code; }
public void PubSub() { using (NetMQContext context = NetMQContext.Create()) { using (WebSocket4Net.WebSocket webSocket = new WebSocket("ws://localhost:82", "WSNetMQ")) { using (WSPublisher publisher = context.CreateWSPublisher()) { publisher.Bind("ws://localhost:82"); ManualResetEvent manualResetEvent = new ManualResetEvent(false); webSocket.Opened += (sender, args) => manualResetEvent.Set(); webSocket.Open(); webSocket.Error += (sender, args) => Console.WriteLine("Error"); manualResetEvent.WaitOne(); Assert.AreEqual(webSocket.State, WebSocketState.Open); byte[] subscription = new byte[3]; subscription[0] = 0; subscription[1] = 1; subscription[2] = (byte)'H'; // should exit the router thread webSocket.Send(subscription, 0, subscription.Length); // wait for the subscription to arrive Thread.Sleep(1000); byte[] receivedMessage = null; manualResetEvent.Reset(); webSocket.DataReceived += (sender, args) => { receivedMessage = args.Data; manualResetEvent.Set(); }; publisher.Send("Hello"); Assert.IsTrue(manualResetEvent.WaitOne(1000)); Assert.AreEqual(0, receivedMessage[0]); Assert.AreEqual('H', receivedMessage[1]); Assert.AreEqual('e', receivedMessage[2]); Assert.AreEqual('l', receivedMessage[3]); Assert.AreEqual('l', receivedMessage[4]); Assert.AreEqual('o', receivedMessage[5]); } } } }
public static int WaitOneOrTwoOrAllOthers(WaitHandle one, WaitHandle two, WaitHandle[] others) { CodeContract.Requires(one != null); CodeContract.Requires(two != null); CodeContract.Requires(others != null && others.Length > 1); var occurredEventIndex = WaitHandle.WaitTimeout; var eventSignaled = new ManualResetEvent(false); var waitOneThread = ThreadUtils.StartBackgroundThread( () => { try { one.WaitOne(); occurredEventIndex = 0; } finally { eventSignaled.Set(); } }); var waitTwoThread = ThreadUtils.StartBackgroundThread( () => { try { two.WaitOne(); occurredEventIndex = 1; } finally { eventSignaled.Set(); } }); var waitOthersThread = ThreadUtils.StartBackgroundThread( () => { try { WaitHandle.WaitAll(others); occurredEventIndex = 2; } finally { eventSignaled.Set(); } }); eventSignaled.WaitOne(); waitOneThread.SafeAbort(); waitTwoThread.SafeAbort(); waitOthersThread.SafeAbort(); return occurredEventIndex; }
public void RequestReply() { using (NetMQContext context = NetMQContext.Create()) { using (WebSocket4Net.WebSocket webSocket = new WebSocket("ws://localhost:82", "WSNetMQ")) { using (WSRouter router = context.CreateWSRouter()) { router.Bind("ws://localhost:82"); ManualResetEvent manualResetEvent = new ManualResetEvent(false); webSocket.Opened += (sender, args) => manualResetEvent.Set(); webSocket.Open(); webSocket.Error += (sender, args) => Console.WriteLine("Error"); manualResetEvent.WaitOne(); Assert.AreEqual(webSocket.State, WebSocketState.Open); byte[] message = new byte[2]; message[0] = 0; message[1] = (byte)'H'; // should exit the router thread webSocket.Send(message, 0, message.Length); byte[] identity = router.Receive(); string msg = router.ReceiveString(); Assert.AreEqual("H", msg); byte[] receivedMessage = null; manualResetEvent.Reset(); webSocket.DataReceived += (sender, args) => { receivedMessage = args.Data; manualResetEvent.Set(); }; router.SendMore(identity).Send("W"); Assert.IsTrue(manualResetEvent.WaitOne(1000)); Assert.AreEqual(0 ,receivedMessage[0]); Assert.AreEqual('W', receivedMessage[1]); } } } }
public void Notify() { var settings = EsFacade.Settings; string server = settings["JabberServer"]; string login = settings["JabberLogin"]; string pass = settings["JabberPassword"]; if (!Validator.HasValue(server, login, pass)) { EsFacade.Logger.Warn("Jabber settings not properly configured."); return; } // we will wait on this event until we're done sending ManualResetEvent done = new ManualResetEvent(false); JabberClient j = new JabberClient { User = login, Server = server, Password = pass, AutoPresence = false, AutoRoster = false, AutoReconnect = -1 }; // listen for errors. Always do this! j.OnError += (o, ex) => { EsFacade.Logger.Error("Jabber notification error.", ex.Message); done.Set(); }; // what to do when login completes j.OnAuthenticate += o => { JabberClient client = (JabberClient)o; client.Message(_to.Jabber, _message); done.Set(); }; // Set everything in motion j.Connect(); // wait until sending a message is complete done.WaitOne(); // logout cleanly j.Close(); }
public override void Execute() { var stopwatch = Stopwatch.StartNew(); Runtime.Connection.JobManager.OpenJob(Job.Id); Runtime.Connection.JobManager.StartJob(); var isJobExecuted = false; var syncObject = new ManualResetEvent(false); TimerCallback callback = _ => { try { var state = Runtime.Connection.JobManager.QueryJobState(Job.Id); switch (state) { case JobState.Completed: isJobExecuted = true; syncObject.Set(); break; case JobState.Failed: isJobExecuted = false; syncObject.Set(); break; default: break; } } catch (Exception) { } }; using (var timer = new Timer(callback, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(100))) { syncObject.WaitOne(); } stopwatch.Stop(); if (isJobExecuted) { Runtime.JobStateExecuted(stopwatch.Elapsed); } else { var errors = Runtime.Connection.JobManager.GetErrorReport(Job.Id); Runtime.JobStateFailed(errors); } }
public static async Task<DateTime?> OpenDatePicker(this DateTime? source) { MakeSureLabelsAreInResources(); var result = source; var page = Client.RootFrame.Content as PhoneApplicationPage; var waiter = new ManualResetEvent(true); if (page != null) { var pageRootPanel = page.Content as Panel; if (pageRootPanel != null) { var datePicker = new PersistentObjectAttributeDatePicker(); datePicker.Value = source; datePicker.RenderTransform = new TranslateTransform { X = -10000, Y = -10000 }; datePicker.Loaded += DatePicker_Loaded; pageRootPanel.Children.Add(datePicker); waiter.Reset(); datePicker.ValueChanged += (sender, e) => { result = e.NewDateTime; waiter.Set(); pageRootPanel.Children.Remove(datePicker); }; var currentPageSource = Client.RootFrame.CurrentSource; NavigatedEventHandler handler = null; handler = delegate { if (currentPageSource == Client.RootFrame.CurrentSource) { waiter.Set(); Client.RootFrame.Navigated -= handler; pageRootPanel.Children.Remove(datePicker); } }; Client.RootFrame.Navigated += handler; } } await Task.Factory.StartNew(() => waiter.WaitOne()); return result; }
///<summary>Blocks the current thread until the transaction completes or the timeout expires.</summary> public static bool WaitForTransactionToComplete(this Transaction me, TimeSpan timeout) { Contract.Requires(me != null); var done = new ManualResetEvent(false); me.TransactionCompleted += (_, __) => done.Set(); if(me.TransactionInformation.Status != TransactionStatus.Active) { done.Set(); } return done.WaitOne(timeout); }
public void TestBasicAckEventHandlerRecovery() { Model.ConfirmSelect(); var latch = new ManualResetEvent(false); ((AutorecoveringModel)Model).BasicAcks += (m, args) => latch.Set(); ((AutorecoveringModel)Model).BasicNacks += (m, args) => latch.Set(); CloseAndWaitForRecovery(); CloseAndWaitForRecovery(); Assert.IsTrue(Model.IsOpen); WithTemporaryNonExclusiveQueue(Model, (m, q) => m.BasicPublish("", q, null, encoding.GetBytes(""))); Wait(latch); }
public void RunningSimpleWorkflow() { WorkflowRuntime runtime = _container.Resolve<WorkflowRuntime>(); ManualResetEvent finished = new ManualResetEvent(false); runtime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) { finished.Set(); }; runtime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e) { finished.Set(); }; WorkflowInstance workflow = runtime.CreateWorkflow(typeof(SimpleWorkflow)); workflow.Start(); bool isFinished = finished.WaitOne(TimeSpan.FromSeconds(1), false); Assert.IsTrue(isFinished, "Workflow must finish in less than a second"); }
public void ExclusiveFileAccess() { // create the test file using(StreamWriter writer = new StreamWriter(File.OpenWrite("test.test"))) { writer.Write("Hello World!"); writer.Close(); } // kick off the thread to do the second open ManualResetEvent first = new ManualResetEvent(false); ManualResetEvent second = new ManualResetEvent(false); ManualResetEvent third = new ManualResetEvent(false); ManualResetEvent fourth = new ManualResetEvent(false); Async.Fork(delegate() { first.WaitOne(); try { using(Stream f = StreamUtil.FileOpenExclusive("test.test")) { Assert.IsNull(f, "file open succeeded when it was expected to fail"); } } catch { third.Set(); fourth.Set(); throw; } second.WaitOne(); third.Set(); try { using(Stream f = StreamUtil.FileOpenExclusive("test.test")) { Assert.IsNotNull(f, "file open failed when it was expected to succeed"); } } catch { fourth.Set(); throw; } fourth.Set(); }, null); // open the file first using(Stream g = StreamUtil.FileOpenExclusive("test.test")) { first.Set(); Thread.Sleep(2000); second.Set(); Thread.Sleep(500); third.WaitOne(); g.Close(); } fourth.WaitOne(); File.Delete("test.test"); }
private void ListenForConnections() { try { // create a blocking TCP/IP stream based server socket serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serversocket.Blocking = true; // bind and listen on the wildcard address IPEndPoint ipepServer = new IPEndPoint(IPAddress.Any, Int32.Parse(settings["PipePortTextBox"])); serversocket.Bind(ipepServer); serversocket.Listen(-1); // notify the foreground thread that we are listening. started.Set(); Logging.Log("ListenForConnections"); // until we are told to Stop while (true) { Socket clientsock = null; try { // block while we accept a new socket connection clientsock = serversocket.Accept(); } catch (SocketException) { // it is likely that the exception being caught here // is that Accept has been interupted by the socket being shutdown // during application exit, so no error is reported. break; } catch (ObjectDisposedException e) { Logging.Log("ObjectDisposedException" + e.Message); break; } catch (InvalidOperationException e) { Logging.Log("InvalidOperationException" + e.Message); break; } if (clientsock.Connected) { lock (associations) { ApplicationEntity scp = GetApplicationEntity("scp"); ApplicationEntity scu = GetApplicationEntity("scu"); Pipe pipe = new Pipe(clientsock, scp, scu, assembly, LoggingCheckBox.Checked); associations.Add(pipe); SetStatus("connection"); UpdateConnections(); } } } } catch (SystemException e) { Logging.Log("SystemException" + e.Message); } finally { // do not leave without signaling that we are accepting connections started.Reset(); } }
} //constructor /// <summary> /// GetOutput is the core worker thread method. /// It peeks at the process streams and if there is output then exits and returns it all. /// If the process exits then it exits after a the loop iterations set in m_LOOPMAX. /// </summary> /// <param name="InObj"></param> public void GetOutput(Object InObj) { try { StreamReader IOStream = null; if (m_IOType == IOType.Output) //Standard Output { lock (m_Process) { IOStream = m_Process.StandardOutput; } //lock } else { if (m_IOType == IOType.Error) //Standard Error { lock (m_Process) { IOStream = m_Process.StandardError; } //lock } //if else //bad input { throw new NotSupportedException("Error in StandardIO class: IO type not found"); } } //else int count = 0; int test = -1; //Main loop to get console output. Wait for any input or timeout once process has exited. while (true) { lock (IOStream) { test = IOStream.Peek(); } //lock if (test > -1) //have output, exit loop { break; } //if else { lock (m_Process) { if (m_Process.HasExited) //start the countdown to exit the loop { count++; } } //lock if (count > m_LOOPMAX) { break; } //if else { Thread.Sleep(m_SLEEPTIME); } //else } //else } //for if (test > -1) //exited loop with output { lock (m_Process) { if (m_IOType == IOType.Output) //Standard Output { lock (m_CallingProcess) { m_CallingProcess.m_StdOut = m_Process.StandardOutput.ReadToEnd(); } //lock } //if else { if (m_IOType == IOType.Error) //Standard Error { lock (m_CallingProcess) { m_CallingProcess.m_StdErr = m_Process.StandardError.ReadToEnd(); } //lock } } //else } //lock } //if else //exited loop through timeout { if (m_IOType == IOType.Output) //Standard Output { m_CallingProcess.m_StdOut = null; } else if (m_IOType == IOType.Error) //Standard Error { m_CallingProcess.m_StdErr = null; } } //else } //try catch (Exception e) { Console.WriteLine("Exception in worker thread: {0}", e.ToString()); } //catch finally { m_WaitHandle.Set(); //Always signal on WaitHandle to avoid deadlocking. } } //GetOutput()
public static string[] runExeBatteryCapacity(string exeFilename, string udid, out int exitCode, int timeout = 300 * 1000, string workingDir = "") { List <string> ret = new List <string>(); exitCode = 1; //string param = $"-u {udid} --logcat --value powerd["; string param = $"-u {udid} --logcat "; Program.logIt($"[runExeBatteryCapacity][{udid}]: ++ exe={exeFilename}, param={param}"); try { var regex = @"Updated Battery Health:.*?MaxCapacity:(\d+) CycleCount:"; if (System.IO.File.Exists(exeFilename)) { DateTime last_output = DateTime.Now; DateTime _start = DateTime.Now; System.Threading.ManualResetEvent ev = new System.Threading.ManualResetEvent(false); Process p = new Process(); p.StartInfo.FileName = exeFilename; p.StartInfo.Arguments = param; p.StartInfo.UseShellExecute = false; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; if (!string.IsNullOrEmpty(workingDir)) { p.StartInfo.WorkingDirectory = workingDir; } p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; //p.EnableRaisingEvents = true; p.OutputDataReceived += (obj, args) => { last_output = DateTime.Now; if (!string.IsNullOrEmpty(args.Data)) { Program.logIt($"[runExeBatteryCapacity][{udid}]: {args.Data}"); var health = Regex.Match(args.Data, regex); if (health.Success) { Console.WriteLine($"MaxCapacity={health.Groups[1].Value}"); Program.logIt($"[runExeBatteryCapacity]: MaxCapacity={health.Groups[1].Value}"); string value = health.Groups[1].Value.Length == 3 ? "100" : health.Groups[1].Value; ret.Add($"MaxCapacity={value}"); //p.Kill(); ev.Set(); } } if (args.Data == null) { ev.Set(); } }; //p.Exited += (o, e) => { ev.Set(); }; p.Start(); _start = DateTime.Now; p.BeginOutputReadLine(); bool process_terminated = false; bool proces_stdout_cloded = false; bool proces_has_killed = false; while (!proces_stdout_cloded || !process_terminated) { if (p.HasExited) { // process is terminated process_terminated = true; Program.logIt($"[runExeBatteryCapacity][{udid}]: process is going to terminate."); ev.Set(); } if (ev.WaitOne(1000)) { // stdout is colsed proces_stdout_cloded = true; Program.logIt($"[runExeBatteryCapacity][{udid}]: stdout pipe is going to close."); if (!p.HasExited) { exitCode = 0; p.Kill(); proces_has_killed = true; Program.logIt($"[runExeBatteryCapacity][{udid}]: process is going to be killed due to timeout."); } } if ((DateTime.Now - last_output).TotalMilliseconds > timeout) { Program.logIt($"[runExeBatteryCapacity][{udid}]: there are {timeout} milliseconds no response. timeout?"); // no output received within timeout milliseconds if (!p.HasExited) { exitCode = 1460; p.Kill(); proces_has_killed = true; Program.logIt($"[runExeBatteryCapacity][{udid}]: process is going to be killed due to timeout."); } } } if (!proces_has_killed) { exitCode = p.ExitCode; } } else { Program.logIt($"[runExeBatteryCapacity][{udid}]: {exeFilename} not exist."); } } catch (Exception ex) { Program.logIt($"[runExeBatteryCapacity][{udid}]: {ex.Message}"); Program.logIt($"[runExeBatteryCapacity][{udid}]: {ex.StackTrace}"); } Program.logIt($"[runExeBatteryCapacity][{udid}]: -- ret={exitCode}"); return(ret.ToArray()); }
public override void NotifyState(ObjectState state) { base.NotifyState(state); if (state == ObjectState.Deactivated) mEvent.Set(); }
public void Dispose() { ThreadExitEvent.Set(); //throw new NotImplementedException (); }
public override void Shutdown() { shutdownEvent.Set(); }
/// <summary> /// Handles the form load, and sets an event to ensure that /// intialization is synchronized with the appearance of the form. /// </summary> /// <param name="e"></param> protected override void OnLoad(System.EventArgs e) { base.OnLoad(e); ControlBox = false; initEvent.Set(); }
internal override void Completed() { completed_event.Set(); }
/// <summary> /// Utility function to terminate the thread /// </summary> private void AbortWork() { abortEvent.Set(); }
public static ShellRequest ProcessCommand(string cmd, string workDirectory, List <string> environmentVars = null) { ShellRequest req = new ShellRequest(); System.Threading.Interlocked.Increment(ref numberOfTasks); //var threadFinish = new System.Threading.ManualResetEvent(false); //threadFinishEvents.Add(threadFinish); System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state) { Process p = null; try { ProcessStartInfo start = CreateProcessStartInfo(cmd, workDirectory, environmentVars); p = Process.Start(start); p.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) { UnityEngine.Debug.LogError(e.Data); }; p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { UnityEngine.Debug.LogError(e.Data); }; p.Exited += delegate(object sender, System.EventArgs e) { UnityEngine.Debug.LogError(e.ToString()); }; bool hasError = false; do { string line = p.StandardOutput.ReadLine(); if (line == null) { break; } line = line.Replace("\\", "/"); lock (_queue) { _queue.Add(delegate() { req.Log(0, line); }); } } while (true); while (true) { string error = p.StandardError.ReadLine(); if (string.IsNullOrEmpty(error)) { break; } hasError = true; lock (_queue) { _queue.Add(delegate() { req.Log(1, error); }); } } p.Close(); lock (_queue) { if (hasError) { _queue.Add(delegate() { req.Error(); }); } else { _queue.Add(delegate() { req.NotifyDone(); }); //直接在线程中触发事件,这个callback中不能用序列化 req.TriggerEdge(); } } } catch (System.Exception e) { UnityEngine.Debug.LogException(e); if (p != null) { p.Close(); } } finally { if (System.Threading.Interlocked.Decrement(ref numberOfTasks) == 0) { threadSignal.Set(); } } }); return(req); }
static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); Helpers.connectionstring_kb_cn = Configuration["cnkbdb"]; Helpers.connectionstring_kb_tq = Configuration["tqkbdb"]; bool stoped = false; isServiceRunning = true; var cts = new CancellationTokenSource(); new Thread(async() => { while (isServiceRunning) { _event1.Reset(); try { using (var db = new Db(Helpers.GetKBConnString(true))) { db.Database.ExecuteSqlCommand(new RawSqlString(@"DELETE from killboard_waiting_api using killboard_kill b WHERE killboard_waiting_api.""killID""=b.""killID"" and (b.""APIverified"" = TRUE or b.""CRESTverified""=TRUE )")); var query = db.killboard_waiting_api.Where(p => p.Error == false || p.Error == null); foreach (var killboardWaitingApi in query) { KmQueue.Enqueue(new KMQueue() { istq = true, waiting = killboardWaitingApi }); } } } catch (Exception e) { Log(e.ToString()); } _event1.Set(); await Task.Delay(5000, cts.Token); } }).Start(); Console.CancelKeyPress += delegate { Log("Shutting Down"); isServiceRunning = false; cts.Cancel(); WaitHandle.WaitAll(events); Log("Exited!"); stoped = true; }; while (!stoped) { Thread.Sleep(1000); } }
public void OnEvent(object sender, DdeEventArgs args) { _Events.Add(args); _Received.Set(); }
private void dbMCSources_OnEventHandler(object obj) { DbMCInterface.ID_EVENT id_event = DbMCInterface.ID_EVENT.Unknown; EventArgs argEventChanged = null; // оборудование для которого произошло событие TEC tec; // для оборудования которой произошло событие Tuple <DbMCInterface.EVENT, bool> tupleConnectHandler; Func <DateTime, TimeSpan> difference = delegate(DateTime target) { // разница целевой даты объекта события и текущей даты return(target - ASUTP.Core.HDateTime.ToMoscowTimeZone()); }; Func <DateTime, bool> isRequired = delegate(DateTime target) { // разница целевой даты объекта события и текущей даты; для проверки необходимости обработки события (только текущие сутки) TimeSpan diff = difference(target); return(diff.TotalDays > -1 && diff.TotalDays < 0); }; Func <DbMCInterface.ID_EVENT, DateTime, DateTime> translate = delegate(DbMCInterface.ID_EVENT id, DateTime datetime) { return(((id == DbMCInterface.ID_EVENT.RELOAD_PLAN_VALUES) || (id == DbMCInterface.ID_EVENT.NEW_PLAN_VALUES)) ? datetime.SystemToLocalHqEx() : ((id == DbMCInterface.ID_EVENT.PHANTOM_RELOAD_PLAN_VALUES) || (id == DbMCInterface.ID_EVENT.REQUEST_PLAN_VALUES)) ? datetime : datetime); }; if (obj is Array) { id_event = (DbMCInterface.ID_EVENT)(obj as object []) [0]; if (id_event == DbMCInterface.ID_EVENT.GENOBJECT_MODIFIED) { Modes.NetAccess.EventRefreshData53500 ev = (obj as object []) [1] as Modes.NetAccess.EventRefreshData53500; #region Подготовка текста сообщения в журнал о событии string msg = string.Empty , listEquipment = string.Empty; msg = string.Format(@"AdminMC::dbMCSources_OnEventHandler((ID_MC_EVENT={1}) - обработчик события - изменения[кол-во={2}]{0}для оборудования {3}..." , Environment.NewLine, id_event, ev.Equipments.Count, @"СПИСОК"); foreach (KeyValuePair <DateTime, List <int> > pair in ev.Equipments) { listEquipment += string.Format(@"[Дата={0}, список=({1})],", pair.Key.ToString(), string.Join(", ", pair.Value)); } listEquipment = listEquipment.Remove(listEquipment.Length - 1); msg = msg.Replace(@"СПИСОК", listEquipment); #endregion Logging.Logg().Action(msg, Logging.INDEX_MESSAGE.NOT_SET); } else if ((id_event == DbMCInterface.ID_EVENT.RELOAD_PLAN_VALUES) || (id_event == DbMCInterface.ID_EVENT.PHANTOM_RELOAD_PLAN_VALUES)) { Modes.NetAccess.EventRefreshJournalMaket53500 ev = (obj as object []) [1] as Modes.NetAccess.EventRefreshJournalMaket53500; DateTime dateTarget; ReadOnlyCollection <Guid> makets; string abbr = string.Empty , taskModes = string.Empty; dateTarget = translate(id_event, ev.dtTarget.GetValueOrDefault()); makets = ev.makets as ReadOnlyCollection <Guid>; abbr = ev.Task.GetAbbr(); taskModes = ev.Task.ModesTaskToString(); Logging.Logg().Action(string.Format(@"AdminMC::dbMCSources_OnEventHandler(ID_MC_EVENT={0}) - обработчик события - переопубликация[на дату={1}, кол-во макетов={2}], Аббр={3}, описание={4}..." , id_event.ToString(), dateTarget.ToString(), makets.Count, abbr, taskModes) , Logging.INDEX_MESSAGE.NOT_SET); if (isRequired(dateTarget) == true) { argEventChanged = new EventArgs <Guid> (id_event, dateTarget, makets); } else { Logging.Logg().Debug($"AdminMC::dbMCSources_OnEventHandler(ID_MC_EVENT={id_event.ToString ()}) - дата нового не актуальна; Day=[{dateTarget}], разн.(сутки)=[{difference (dateTarget).TotalDays}]..." , Logging.INDEX_MESSAGE.NOT_SET); } } else if ((id_event == DbMCInterface.ID_EVENT.NEW_PLAN_VALUES) || (id_event == DbMCInterface.ID_EVENT.REQUEST_PLAN_VALUES)) { Modes.NetAccess.EventPlanDataChanged ev = (obj as object []) [1] as Modes.NetAccess.EventPlanDataChanged; DateTime day , version; string pbr_number = string.Empty , id_mc_tec = string.Empty; int id_gate = -1; day = translate(id_event, ev.Day); pbr_number = ev.Type.PlanTypeToString(); version = translate(id_event, ev.Version); id_mc_tec = ev.ClientId; id_gate = ev.IdGate; Logging.Logg().Action(string.Format(@"AdminMC::dbMCSources_OnEventHandler(ID_MC_EVENT={0}) - обработчик события - {6} план[на дату={1}, номер={2}, версия={3}, для подразделения={4}, IdGate={5}]..." , id_event.ToString(), day.ToString(), pbr_number, version.ToString(), id_mc_tec, id_gate , id_event == DbMCInterface.ID_EVENT.NEW_PLAN_VALUES ? "новый" : id_event == DbMCInterface.ID_EVENT.REQUEST_PLAN_VALUES ? "<запрос>" : "НЕ ИЗВЕСТНО") , Logging.INDEX_MESSAGE.NOT_SET); // проверить дату за которую получен новый план: только сегодняшние и следующие сутки сутки if (isRequired(day) == true) { tec = m_list_tec.Find(t => { return(t.name_MC.Trim().Equals(id_mc_tec.ToString())); }); argEventChanged = new EventArgs <FormChangeMode.KeyDevice> (id_event, day, new ReadOnlyCollection <FormChangeMode.KeyDevice> ( allTECComponents.FindAll(comp => { return((comp.IsGTP == true) && (comp.tec.m_id == tec.m_id)); }).ConvertAll(comp => new FormChangeMode.KeyDevice() { Id = comp.m_id, Mode = FormChangeMode.MODE_TECCOMPONENT.GTP }) )); } else { Logging.Logg().Debug($"AdminMC::dbMCSources_OnEventHandler(ID_MC_EVENT={id_event.ToString ()}) - дата не актуальная; Day=[{day}], разн.(сутки)=[{difference (day).TotalDays}]..." , Logging.INDEX_MESSAGE.NOT_SET); } } else { ; } // проверить сфорирован ли аргумент для события // , имеется ли обработчик; иначе из коллекции не смогут быть удалены элементы(удаление только из-вне) // , а значит коллекция увеличивается без ограничений, а элементы никаким образом не обрабатываются if ((Equals(argEventChanged, null) == false) && (isHandlerMCEvent(id_event) == true)) { AddEvent(argEventChanged); } else { ; } } else if (typeof(Tuple <DbMCInterface.EVENT, bool>).IsAssignableFrom(obj.GetType()) == true) { //TODO: ретранслировать для формы произошла подписка/отписка от события Модес-Центра tupleConnectHandler = obj as Tuple <DbMCInterface.EVENT, bool>; _dictNotify [DbMCInterface.ID_EVENT.HANDLER_CONNECT]?.Invoke(this, new EventArgs <bool>(DbMCInterface.TranslateEvent(tupleConnectHandler.Item1), DateTime.MinValue, new ReadOnlyCollection <bool> (new List <bool>() { tupleConnectHandler.Item2 }))); } else if (typeof(bool).IsAssignableFrom(obj.GetType()) == true) { id_event = DbMCInterface.ID_EVENT.Unknown; //TODO: проверить результат попытки установки соединения Logging.Logg().Action($"AdminMC::dbMCSources_OnEventHandler(ID_MC_EVENT={id_event.ToString ()}) - изменение состояния соединения УСТАНОВЛЕНО = {(bool)obj})...", Logging.INDEX_MESSAGE.NOT_SET); switch ((bool)obj == true ? 1 : 0) { case 0: _eventConnected.Reset(); break; case 1: _eventConnected.Set(); FetchEvent(false); break; default: break; } } else { throw new Exception(@"AdminMC::dbMCSources_OnEventHandler () - неизвестное событие от DbMCSources..."); } }
/// <summary> /// Moves the mesh currently in the temporary mesh buffer into the mesh structure itself, /// with material information from the asset properties. /// </summary> /// <param name="assetProps">Material information to use</param> private void AddFacetsInternal(AssetProperties assetProps) { if (tmpSurface.vertCount > TMP_VERTICIES) { // This is just bad. It could be fixed by exporting it per-face instead of with a single block. System.Windows.Forms.MessageBox.Show("Warning: Mesh segment exceededed " + TMP_VERTICIES + " verticies. Strange things may begin to happen."); } // If adding this would cause the sub mesh to overflow dump what currently exists. if (tmpSurface.vertCount + postSurface.vertCount >= TMP_VERTICIES) { DumpMeshBuffer(); } Array.Copy(tmpSurface.verts, 0, postSurface.verts, postSurface.vertCount * 3, tmpSurface.vertCount * 3); Array.Copy(tmpSurface.norms, 0, postSurface.norms, postSurface.vertCount * 3, tmpSurface.vertCount * 3); #if USE_TEXTURES Array.Copy(tmpSurface.textureCoords, 0, postSurface.textureCoords, postSurface.vertCount * 2, tmpSurface.vertCount * 2); #endif BXDAMesh.BXDASurface nextSurface = new BXDAMesh.BXDASurface(); nextSurface.color = 0xFFFFFFFF; if (assetProps.color != null) { nextSurface.hasColor = true; nextSurface.color = ((uint)assetProps.color.Red << 0) | ((uint)assetProps.color.Green << 8) | ((uint)assetProps.color.Blue << 16) | ((((uint)(assetProps.color.Opacity * 255)) & 0xFF) << 24); } nextSurface.transparency = (float)assetProps.transparency; nextSurface.translucency = (float)assetProps.translucency; nextSurface.specular = (float)assetProps.specular; nextSurface.indicies = new int[tmpSurface.facetCount * 3]; // Raw copy the indicies for now, then fix the offset in a background thread. Array.Copy(tmpSurface.indicies, nextSurface.indicies, nextSurface.indicies.Length); #region Fix Index Buffer Offset // Make sure we haven't exceeded the maximum number of background tasks. if (waitingThreads.Count > MAX_BACKGROUND_THREADS) { // Console.WriteLine("Got ahead of ourselves...."); System.Threading.WaitHandle.WaitAll(waitingThreads.ToArray()); waitingThreads.Clear(); } { System.Threading.ManualResetEvent lockThing = new System.Threading.ManualResetEvent(false); waitingThreads.Add(lockThing); int offset = postSurface.vertCount; int backingFacetCount = tmpSurface.facetCount; System.Threading.ThreadPool.QueueUserWorkItem(delegate(object obj) { for (int i = 0; i < backingFacetCount * 3; i++) { nextSurface.indicies[i] = nextSurface.indicies[i] + offset - 1; // Inventor has one-based indicies. Zero-based is the way to go for everything except Inventor. } lockThing.Set(); }, waitingThreads.Count); } #endregion postSurfaces.Add(nextSurface); postSurface.facetCount += tmpSurface.facetCount; postSurface.vertCount += tmpSurface.vertCount; }
public static string[] runExe(string exeFilename, string param, out int exitCode, int timeout = 60 * 1000, string workingDir = "") { List <string> ret = new List <string>(); exitCode = 1; Program.logIt(string.Format("[runExe]: ++ exe={0}, param={1}", exeFilename, param)); try { if (System.IO.File.Exists(exeFilename)) { DateTime last_output = DateTime.Now; DateTime _start = DateTime.Now; System.Threading.ManualResetEvent ev = new System.Threading.ManualResetEvent(false); Process p = new Process(); p.StartInfo.FileName = exeFilename; p.StartInfo.Arguments = param; p.StartInfo.UseShellExecute = false; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; if (!string.IsNullOrEmpty(workingDir)) { p.StartInfo.WorkingDirectory = workingDir; } p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; //p.EnableRaisingEvents = true; p.OutputDataReceived += (obj, args) => { last_output = DateTime.Now; if (!string.IsNullOrEmpty(args.Data)) { Program.logIt(string.Format("[runExe]: {0}", args.Data)); ret.Add(args.Data); } if (args.Data == null) { ev.Set(); } }; //p.Exited += (o, e) => { ev.Set(); }; p.Start(); _start = DateTime.Now; p.BeginOutputReadLine(); bool process_terminated = false; bool proces_stdout_cloded = false; bool proces_has_killed = false; while (!proces_stdout_cloded || !process_terminated) { if (p.HasExited) { // process is terminated process_terminated = true; Program.logIt(string.Format("[runExe]: process is going to terminate.")); } if (ev.WaitOne(1000)) { // stdout is colsed proces_stdout_cloded = true; Program.logIt(string.Format("[runExe]: stdout pipe is going to close.")); } if ((DateTime.Now - last_output).TotalMilliseconds > timeout) { Program.logIt(string.Format("[runExe]: there are {0} milliseconds no response. timeout?", timeout)); // no output received within timeout milliseconds if (!p.HasExited) { exitCode = 1460; p.Kill(); proces_has_killed = true; Program.logIt(string.Format("[runExe]: process is going to be killed due to timeout.")); } } } if (!proces_has_killed) { exitCode = p.ExitCode; } } else { Program.logIt(string.Format("[runExe]: {0} not exist.", exeFilename)); } } catch (Exception ex) { Program.logIt(string.Format("[runExe]: {0}", ex.Message)); Program.logIt(string.Format("[runExe]: {0}", ex.StackTrace)); } Program.logIt(string.Format("[runExe]: -- ret={0}", exitCode)); return(ret.ToArray()); }
/// <summary> /// resumes the encoding process /// </summary> /// <param name="error">output for any errors that might ocurr during this method</param> /// <returns>true if encoding has been successfully started, false if not</returns> public bool resume() { return(mre.Set()); }
/// <summary> /// Instantiates an Engine and uses the the instance to perform the request prepared in the constructor of the ComputationJob class. /// </summary> public override void Perform() { base.Perform(); Process currentP = Process.GetCurrentProcess(); currentP.Refresh(); JobManager.JobManagerTrace.TraceVerbose(string.Format("{0}:Start of job mem stats: working set {1}Mb, GC.allocated {2}Mb, PrivateMem {3}Mb", this.ToShortString(), Environment.WorkingSet / 1024 / 1024, GC.GetTotalMemory(false) / 1024 / 1024, currentP.PrivateMemorySize64 / 1024 / 1024)); var config = configProvider.GetConfiguration(this.Request.ReproducibilityTimestamp); JobManager.JobManagerTrace.TraceVerbose("{0}: FE type determined {1}. Loading FE assembly", this.ToShortString(), config.FetchEngineTypeName); var feType = Type.GetType(config.FetchEngineTypeName); if (feType == null) { throw new InvalidOperationException("Cannot load fetch engine type " + feType); } JobManager.JobManagerTrace.TraceVerbose("{0}: FE assembly loaded", this.ToShortString()); var feConst = feType.GetConstructor(new Type[1] { typeof(IExtendedConfigurationProvider) }); if (feConst == null) { throw new InvalidOperationException("The FE constrictor with needed signature is not found. Are the currently running service assemblies and math assemblies from AzureGAC built with different Core assemblies?"); } JobManager.JobManagerTrace.TraceVerbose("{0}: FE assembly loaded", this.ToShortString()); var fe = (IFetchEngine)feConst.Invoke(new object[1] { configProvider }); JobManager.JobManagerTrace.TraceVerbose("{0}: FE instance constructed", this.ToShortString()); IFetchResponseWithProvenance result = null; System.Threading.ManualResetEvent isDone = new System.Threading.ManualResetEvent(false); bool isWorkingThreadAborted = false; Exception executionException = null; //TODO: seems like spawning a thread is not necessary anymore -- check! workingThread = new System.Threading.Thread(new System.Threading.ThreadStart(() => { try { Stopwatch sw = new Stopwatch(); sw.Start(); result = fe.PerformRequestAsync(this.Request).Result; sw.Stop(); JobManager.JobManagerTrace.TraceVerbose("{0}: FE processed the request in {1}. Writing data to blob...", this.ToShortString(), sw.Elapsed); if (result.Provenance != null) { this.PutProvenance(result.Provenance); } this.PutValues(result.Values); this.PutUncertaties(result.Uncertainty); } catch (ThreadAbortException) { JobManager.JobManagerTrace.TraceInfo("{0}: Working thread is aborted (due to heavy part calculation cancelation?)", this.ToShortString()); isWorkingThreadAborted = true; } catch (Exception exc) { JobManager.JobManagerTrace.TraceError("{0}: Exception in working thread: {1}", this.ToShortString(), exc.ToString()); executionException = exc; } finally { isDone.Set(); } } )); workingThread.IsBackground = true; JobManager.JobManagerTrace.TraceInfo("{0}: Starting working thread", this.ToShortString()); workingThread.Start(); isDone.WaitOne(); JobManager.JobManagerTrace.TraceInfo("{0}: Working thread signaled that it is finished. Joining it", this.ToShortString()); workingThread.Join(); JobManager.JobManagerTrace.TraceVerbose("{0}: Joined worker thread", this.ToShortString()); if (isWorkingThreadAborted) { this.Abandon(); } else { this.Complete(executionException == null); } JobManager.JobManagerTrace.TraceInfo("{0}: marked as {1}", this.ToShortString(), isWorkingThreadAborted ? "Pending" : "Complete"); currentP.Refresh(); JobManager.JobManagerTrace.TraceVerbose(string.Format("{0}:End of job mem stats: working set {1}Mb, GC.allocated {2}Mb, PrivateMem {3}Mb", this.ToShortString(), Environment.WorkingSet / 1024 / 1024, GC.GetTotalMemory(false) / 1024 / 1024, currentP.PrivateMemorySize64 / 1024 / 1024)); }
/// ------------------------------------------------------------------- /// <summary> /// Method that is called from the inherited OnEvent() and will store the event in the _eventList ArrayList. /// </summary> /// ------------------------------------------------------------------- internal void OnEvent(object eventElement, object argument) { // Validate the element by calling something on it AutomationElement element = null; if (eventElement is AutomationElement) { element = eventElement as AutomationElement; } string elName = Helpers.GetXmlPathFromAutomationElement(element); string uiSpyLook = Library.GetUISpyLook(element); Comment("Got event on...({0})", uiSpyLook); #pragma warning suppress 6517 lock (this) { // Let WaitForEvents() know when the last event has occured. _lastEvent = DateTime.Now; if (_eventList == null) { _eventList = new ArrayList(); } // Stop here and wait until we are ready to process events by a call into WaitForEvents(). _haveNotifiedEvent.WaitOne(1000, true); EventItem ei = new EventItem(element, argument); int i = _eventList.Add(ei); StringBuilder buffer = new StringBuilder(" FIRED!! EVENT[" + i + "/" + _eventList.Count + "](" + uiSpyLook + ")...INFO("); if (argument is AutomationPropertyChangedEventArgs) { AutomationPropertyChangedEventArgs arg = argument as AutomationPropertyChangedEventArgs; if (arg == null) { throw new ArgumentException(); } buffer.Append(arg.Property.ProgrammaticName + " Property[" + arg.Property + "] NewValue[" + arg.NewValue + "] OldValue[" + arg.OldValue + "])"); } else { if (argument is AutomationEventArgs) { AutomationEventArgs arg = argument as AutomationEventArgs; if (arg == null) { throw new ArgumentException(); } buffer.Append(arg.EventId.ProgrammaticName + ")"); } else { if (argument is StructureChangedEventArgs) { StructureChangedEventArgs arg = argument as StructureChangedEventArgs; if (arg == null) { throw new ArgumentException(); } Comment("StructureChangedEventArgs:" + ((StructureChangedEventArgs)argument).StructureChangeType.ToString()); buffer.Append(arg.EventId.ProgrammaticName + ") StructureChangeType[" + arg.StructureChangeType.ToString() + "])"); } else { if (argument is WindowClosedEventArgs) { Comment("WindowClosedEventArgs"); WindowClosedEventArgs arg = argument as WindowClosedEventArgs; if (arg == null) { throw new ArgumentException(); } buffer.Append(arg.EventId.ProgrammaticName + ")"); } else { if (argument is AutomationFocusChangedEventArgs) { AutomationFocusChangedEventArgs arg = argument as AutomationFocusChangedEventArgs; if (arg == null) { throw new ArgumentException(); } buffer.Append(arg.EventId.ProgrammaticName + ") ChildId[" + arg.ChildId + "] ObjectId[" + arg.ObjectId + "])"); } } } } } Comment(buffer.ToString() + " Control Path = " + elName); // _haveNotifiedEvent.Reset() will let _haveNotifiedEvent.WaitOne() to pause at the top of this procedure next time in. _haveNotifiedEvent.Reset(); // _gotNotifiedEvent.Set() will allow WaitForEvents() to continue to process at the _gotNotifiedEvent.WaitOne() call. _gotNotifiedEvent.Set(); } }
public override void Abort() { AbortHandle.Set(); }
private void Unpause_Click(object sender, EventArgs e) { ShowPause(false, null); m_pause.Set(); }
private void ListenForConnections() { try { // create a blocking TCP/IP stream based server socket // replaced AddressFamily.InterNetwork with AddressFamily.InterNetworkV6 to support IPv6. serversocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); serversocket.Blocking = true; // 27 is equivalent to IPV6_V6ONLY socket option in the winsock code libary. serversocket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0); // bind and listen on the IPv4 and IPv6 wildcard address. IPEndPoint ipepServer = new IPEndPoint(IPAddress.IPv6Any, port); serversocket.Bind(ipepServer); serversocket.Listen(-1); // notify the foreground thread that we are listening. started.Set(); Logging.Log("ListenForConnections"); // until we are told to Stop while (true) { Socket clientsock = null; try { // block while we accept a new socket connection clientsock = serversocket.Accept(); } catch (SocketException) { // it is likely that the exception being caught here // is that Accept has been interupted by the socket being shutdown // during application exit, so no error is reported. break; } catch (ObjectDisposedException e) { Logging.Log("ObjectDisposedException" + e.Message); break; } catch (InvalidOperationException e) { Logging.Log("InvalidOperationException" + e.Message); break; } if (clientsock.Connected) { lock (associations) { // we got one, setup a file server session for this socket Association association = new Association(clientsock, services, hosts); associations.Add(association); UpdateConnections(); } } } } catch (SystemException e) { Logging.Log("SystemException" + e.Message); } finally { // do not leave without signaling that we are accepting connections started.Reset(); } }
private void Yesbtn_Click(object sender, EventArgs e) { label1.Text = ""; chno += (int)Math.Pow(2.0, cardno); mre.Set(); }