public override Task<Result> Scan(MobileBarcodeScanningOptions options) { var rootFrame = RootFrame ?? Window.Current.Content as Frame ?? ((FrameworkElement) Window.Current.Content).GetFirstChildOfType<Frame>(); var dispatcher = Dispatcher ?? Window.Current.Dispatcher; return Task.Factory.StartNew(new Func<Result>(() => { var scanResultResetEvent = new System.Threading.ManualResetEvent(false); Result result = null; ScanPage.ScanningOptions = options; ScanPage.ResultFoundAction = (r) => { result = r; scanResultResetEvent.Set(); }; ScanPage.UseCustomOverlay = this.UseCustomOverlay; ScanPage.CustomOverlay = this.CustomOverlay; ScanPage.TopText = TopText; ScanPage.BottomText = BottomText; dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { rootFrame.Navigate(typeof(ScanPage)); }); scanResultResetEvent.WaitOne(); return result; })); }
public NetzService(string[] args) { this.args = args; resetEvent = new System.Threading.ManualResetEvent(false); ServiceName = ProjectInstaller.SERVICENAME; Init(); }
public void SendMessage_Test() { RequestMessage message = new RequestMessage() { Device = "test", Level = MessageLevel.High, Message = "test", Source = "unitest", Title = "test" }; ResponseMessage resmessage = CatsAgent.SendMessage(message); var t1 = resmessage.Message; var t2 = resmessage.Result; Assert.IsTrue(t1.Length > 0); Assert.AreEqual(t2, MessageSendingResult.Succeed); System.Threading.ManualResetEvent hand = new System.Threading.ManualResetEvent(false); CatsAgent.SendMessageAsync(message, new Action<ResponseMessage>((ar) => { hand.Set(); })); hand.WaitOne(); }
public void ConnectionManagerAddsNewServicesFromServiceDiscovery() { var manualResetEvent = new System.Threading.ManualResetEvent(false); var serviceUri1 = new ServiceUri() { Address = "1" }; var serviceUri2 = new ServiceUri() { Address = "2" }; Dictionary<ServiceUri, PerformanceStatistics> services = new Dictionary<ServiceUri, PerformanceStatistics>() { {serviceUri1, new PerformanceStatistics()}, {serviceUri2, new PerformanceStatistics()} }; var serviceDiscoveryMock = new Mock<IServiceDiscovery>(MockBehavior.Strict); serviceDiscoveryMock.Setup(sd => sd.GetPerformanceStatistics()).Returns(() => services).Callback(() => manualResetEvent.Set()); var manager = new ConnectionManager(remoteService: null, listener: null, serviceDiscovery: serviceDiscoveryMock.Object, serviceDiscoveryPeriod: new TimeSpan(days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds: 10)); manualResetEvent.WaitOne(); manager.RemoteServices.Count().ShouldBe(2); services.Add(new ServiceUri(), new PerformanceStatistics()); manualResetEvent.Reset(); manualResetEvent.WaitOne(); manager.RemoteServices.Count().ShouldBe(3); }
private void RunItems(List<WaitItem> waitItems) { try { System.Threading.ManualResetEvent[] mre = new System.Threading.ManualResetEvent[waitItems.Count]; for (int i = 0; i < waitItems.Count; i++) { mre[i] = waitItems[i].MRE; } foreach (WaitItem item in waitItems) { item.MRE.Reset(); System.Threading.ThreadPool.QueueUserWorkItem(ThreadExecute, item); } System.Threading.WaitHandle.WaitAll(mre); foreach (WaitItem item in waitItems) { if (item.Error != null) throw item.Error; } } finally { foreach (WaitItem item in waitItems) { Push(item); } waitItems.Clear(); } }
public DbThreadsGator(bool gateIsOpen) { if (gateIsOpen) gate = new System.Threading.ManualResetEvent(true); else gate = new System.Threading.ManualResetEvent(false); }
public override Task<Result> Scan(MobileBarcodeScanningOptions options) { return Task.Factory.StartNew(new Func<Result>(() => { var scanResultResetEvent = new System.Threading.ManualResetEvent(false); Result result = null; //Navigate: /ZxingSharp.WindowsPhone;component/Scan.xaml ScanPage.ScanningOptions = options; ScanPage.ResultFoundAction = (r) => { result = r; scanResultResetEvent.Set(); }; ScanPage.UseCustomOverlay = this.UseCustomOverlay; ScanPage.CustomOverlay = this.CustomOverlay; ScanPage.TopText = TopText; ScanPage.BottomText = BottomText; Dispatcher.BeginInvoke(() => { ((Microsoft.Phone.Controls.PhoneApplicationFrame)Application.Current.RootVisual).Navigate( new Uri("/ZXingNetMobile;component/ScanPage.xaml", UriKind.Relative)); }); scanResultResetEvent.WaitOne(); return result; })); }
public AgentThreadInfo(System.Threading.Thread thread) { if (object.ReferenceEquals(thread, null)) { throw new ArgumentNullException("thread"); } this.Thread = thread; this.MainReset = new System.Threading.ManualResetEvent(false); this.AgentReset = new System.Threading.ManualResetEvent(false); }
public ADTFile(WDTFile wdt, string fileName, uint indexX, uint indexY, bool initial = false) { bool unkFlag = (wdt.Flags & 0x84) != 0; if (unkFlag) throw new Exception(); IndexX = indexX; IndexY = indexY; FileName = fileName; mLoadEvent = new System.Threading.ManualResetEvent(false); if (initial == false) { Game.GameManager.ThreadManager.LaunchThread( () => { try { AsyncLoadProc(); } catch (Exception) { } } ); } else AsyncLoadProc(); ADTManager.AddADT(this); }
private static void ExecuteAndWaitForSSHCommand(string IPAddress,string command) { var handle = new System.Threading.ManualResetEvent(false); var helper = new SshCommandHelper(IPAddress, handle); helper.WriteSSHCommand(command, true); handle.WaitOne(); }
static void Main() { System.Threading.ManualResetEvent close = new System.Threading.ManualResetEvent(false); SystemEvents.SessionEnding += (object sender, SessionEndingEventArgs e) => close.Set(); BaseClass(); close.WaitOne(); }
public Control(string ServerAddress, int Port, ref CarverLab.Utility.Logger logger) { log = logger; m_sServerAddress = ServerAddress; m_iPort = Port; m_TCPClient = new System.Net.Sockets.TcpClient(); m_EventChannelConnectionComplete = new System.Threading.ManualResetEvent(false); m_sLastError = ""; m_EventReceivedFile = new System.Threading.AutoResetEvent(false); }
public Control(string ServerAddress, int Port) { log = new Logger(AppInfo.Title + Port); m_sServerAddress = ServerAddress; m_iPort = Port; m_TCPClient = new System.Net.Sockets.TcpClient(); m_EventChannelConnectionComplete = new System.Threading.ManualResetEvent(false); m_sLastError = ""; m_EventReceivedFile = new System.Threading.AutoResetEvent(false); }
public PeriodicOutput(ConsoleOutput messageSink, TimeSpan updateFrequency) { m_output = messageSink; m_readyEvent = new System.Threading.ManualResetEvent(false); m_finishEvent = new System.Threading.ManualResetEvent(false); m_updateFrequency = updateFrequency; m_thread = new System.Threading.Thread(this.ThreadMain); m_thread.IsBackground = true; m_thread.Name = "Periodic console writer"; m_thread.Start(); }
static void Parse() { var e = new System.Threading.ManualResetEvent(false); Console.WriteLine ("Parsing..."); GlobalParseCache.BeginAddOrUpdatePaths (new[]{ srcDir }, false, (ea) => { Console.WriteLine ("Finished parsing. {0} files. {1} ms.", ea.FileAmount, ea.ParseDuration); e.Set(); }); e.WaitOne (); }
internal bool m_UpdateRequired { get; set; } //true if this command updates a polled status variable, and an update is needed ASAP /// <summary> /// /// </summary> /// <param name="command">actual serial command to be sent, not including ending '#' or the native checksum</param> /// <param name="timeout">timeout value for this command in msec, -1 if no timeout wanted</param> /// <param name="wantResult">does the caller want the result returned by Gemini?</param> /// <param name="bRaw">command is a raw string to be passed to the device unmodified</param> internal CommandItem(string command, int timeout, bool wantResult, bool bRaw) { m_Command = command; m_ThreadID = System.Threading.Thread.CurrentThread.ManagedThreadId; m_Timeout = timeout; // create a wait handle if result is desired if (wantResult) m_WaitForResultHandle = new System.Threading.ManualResetEvent(false); m_Result = null; m_Raw = bRaw; }
public UwaUdpSocket(int localPort, string localIPAddress) { _DataAvailableSignal = new System.Threading.ManualResetEvent(false); _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue<ReceivedUdpData>(); this._LocalPort = localPort; _Socket = new Windows.Networking.Sockets.DatagramSocket(); _Socket.MessageReceived += _Socket_MessageReceived; BindSocket(); }
protected void Application_End() { if (_reaper != null) { _reaperQuit.Set(); _reaper.Join(); _reaper = null; _reaperQuit.Dispose(); _reaperQuit = null; } Game.WorldData.Shutdown(); }
public UwaUdpSocket(int localPort) { _DataAvailableSignal = new System.Threading.ManualResetEvent(false); _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue<ReceivedUdpData>(); this.localPort = localPort; _Socket = new Windows.Networking.Sockets.DatagramSocket(); _Socket.MessageReceived += _Socket_MessageReceived; var t = _Socket.BindServiceNameAsync(this.localPort.ToString()).AsTask(); t.Wait(); }
public ADTFile(string fileName, uint indexX, uint indexY, bool initial = false) { IndexX = indexX; IndexY = indexY; FileName = fileName; mLoadEvent = new System.Threading.ManualResetEvent(false); if (initial == false) Game.GameManager.ThreadManager.LaunchThread(AsyncLoadProc); else AsyncLoadProc(); ADTManager.AddADT(this); }
public async Task RunAsync ( Action act ) { await Task.Run ( ( ) => { System.Threading.ManualResetEvent evt = new System.Threading.ManualResetEvent ( false ); m_dispatcher.BeginInvoke ( ( ) => { act ( ); evt.Set ( ); } ); evt.WaitOne ( ); } ); }
public override Task<Result> Scan (MobileBarcodeScanningOptions options) { return Task.Factory.StartNew(() => { try { var scanResultResetEvent = new System.Threading.ManualResetEvent(false); Result result = null; this.appController.InvokeOnMainThread(() => { // Free memory first and release resources if (viewController != null) { viewController.Dispose(); viewController = null; } viewController = new ZxingCameraViewController(options, this); viewController.BarCodeEvent += (BarCodeEventArgs e) => { viewController.DismissViewController(); result = e.BarcodeResult; scanResultResetEvent.Set(); }; viewController.Canceled += (sender, e) => { viewController.DismissViewController(); scanResultResetEvent.Set(); }; appController.PresentViewController(viewController, true, () => { }); }); scanResultResetEvent.WaitOne(); return result; } catch (Exception ex) { return null; } }); }
public void RunUpdate() { var u = Updater.Instance; var waitHandler = new System.Threading.ManualResetEvent(false); u.NoUpdatesFound += (s, e) => waitHandler.Set(); u.Error += (s, e) => waitHandler.Set(); u.ExternalUpdateStarted += (s, e) => waitHandler.Set(); u.UpdateCancelled += (s, e) => waitHandler.Set(); Updater.CheckUpdateSimple(); waitHandler.WaitOne(); }
public CSharp_FastCompiler() { DebugMode = false; // set to true to see details about each AstCreation and Compilation stage DebugMode = true; InvocationParameters = new Dictionary<string, object>(); ExtraSourceCodeFilesToCompile = new List<String>(); ReferencedAssemblies = getDefaultReferencedAssemblies(); default_MethodName = "dynamicMethod"; default_TypeName = "DynamicType"; generateDebugSymbols = false; //OriginalCodeSnippet = ""; SourceCode = ""; FinishedCompilingCode = new System.Threading.ManualResetEvent(true); // defaults }
public BacnetAsyncResult(BacnetClient comm, BacnetAddress adr, byte invoke_id, byte[] transmit_buffer, int transmit_length, bool wait_for_transmit, int transmit_timeout) { m_transmit_timeout = transmit_timeout; m_adr = adr; m_wait_for_transmit = wait_for_transmit; m_transmit_buffer = transmit_buffer; m_transmit_length = transmit_length; AsyncWaitHandle = new System.Threading.ManualResetEvent(false); m_comm = comm; m_wait_invoke_id = invoke_id; m_comm.OnComplexAck += new BacnetClient.ComplexAckHandler(m_comm_OnComplexAck); m_comm.OnError += new BacnetClient.ErrorHandler(m_comm_OnError); m_comm.OnAbort += new BacnetClient.AbortHandler(m_comm_OnAbort); m_comm.OnSimpleAck += new BacnetClient.SimpleAckHandler(m_comm_OnSimpleAck); m_comm.OnSegment += new BacnetClient.SegmentHandler(m_comm_OnSegment); }
static void Main(string[] args) { //Load initial settings Logger.Logger.Get("Runner").Message("App started"); //Logger.Logger.Get().Message("App started"); WorkerProcess.GetInstance().Process(); System.Threading.ManualResetEvent _quitEvent = new System.Threading.ManualResetEvent(false); Console.CancelKeyPress += (sender, eArgs) => { _quitEvent.Set(); eArgs.Cancel = true; }; _quitEvent.WaitOne(); }
protected void Application_Start() { // AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); // Automatically delete timed out sessions in our table. _reaperQuit = new System.Threading.ManualResetEvent(false); _reaper = new System.Threading.Thread(new System.Threading.ThreadStart(() => { while (!_reaperQuit.WaitOne(30000)) { Climoo.Session.SessionManager.GrimReaper(); } })); _reaper.Start(); Game.WorldData.Init(); }
public UwaUdpSocket(string ipAddress, int multicastTimeToLive, int localPort) { _DataAvailableSignal = new System.Threading.ManualResetEvent(false); _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue<ReceivedUdpData>(); this.ipAddress = ipAddress; this.multicastTimeToLive = multicastTimeToLive; this.localPort = localPort; _Socket = new Windows.Networking.Sockets.DatagramSocket(); //_Socket.Control.MulticastOnly = true; _Socket.MessageReceived += _Socket_MessageReceived; var t = _Socket.BindServiceNameAsync(this.localPort.ToString()).AsTask(); t.Wait(); _Socket.JoinMulticastGroup(new Windows.Networking.HostName(Rssdp.Infrastructure.SsdpConstants.MulticastLocalAdminAddress)); }
public CSharp_FastCompiler() { DebugMode = false; // set to true to see details about each AstCreation and Compilation stage //DebugMode = true; ResolveInvocationParametersType = true; UseCachedAssemblyIfAvailable = true; InvocationParameters = new Dictionary<string, object>(); ExtraSourceCodeFilesToCompile = new List<String>(); ReferencedAssemblies = CompileEngine.DefaultReferencedAssemblies; default_MethodName = "dynamicMethod"; default_TypeName = "DynamicType"; generateDebugSymbols = false; //OriginalCodeSnippet = ""; SourceCode = ""; FinishedCompilingCode = new System.Threading.ManualResetEvent(true); CompilationVersion = (Environment.Version.Major.eq(4)) ? "v4.0" : "v3.5"; // defaults }
internal static com.citrix.xenclient.xenmgr.diag.diagService CreateDbusDiag(out Udbus.Core.ServiceConnectionParams serviceConnectionParams, Udbus.Core.Logging.ILog log, Udbus.Serialization.UdbusDelegates.D_io_debug io_debug) { // Create a V4V connection. Udbus.v4v.v4vConnection connection; System.Threading.ManualResetEvent stop = new System.Threading.ManualResetEvent(false); DbusHosts.GetV4vConnection(out connection, out serviceConnectionParams, io_debug, stop, log ); // Use dbus interface to xenmgr.diag. Udbus.Serialization.DbusConnectionParameters dbusConnectionParameters = com.citrix.xenclient.xenmgr.diag.diagService.DefaultConnectionParameters; dbusConnectionParameters.Destination = "com.citrix.xenclient.xenmgr"; com.citrix.xenclient.xenmgr.diag.diagService diag = com.citrix.xenclient.xenmgr.diag.diagService.Create(serviceConnectionParams, dbusConnectionParameters); return diag; }
public AssemblyPackageContainer GetAssemblyPackages(IEnumerable <AssemblyPart> assemblyParts) { var allDone = new System.Threading.ManualResetEvent(false); var asyncResult = new Threading.AsyncResult <AssemblyPackageContainer>(ar => { try { allDone.Set(); } catch (System.IO.IOException) { try { allDone.Dispose(); } catch { } } }, null); var arguments = new object[] { asyncResult, assemblyParts }; DoGetAssemblyPackages(arguments); try { allDone.WaitOne(); } catch (ObjectDisposedException) { } if (asyncResult.Exception != null) { throw asyncResult.Exception; } return(asyncResult.Result); }
static void Main(string[] args) { Console.Title = "Ideal Server - TCP Hole Punching Proof of Concept"; Incoming = new NetworkPeer(); Incoming.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true); Incoming.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); Console.Write("Incoming: Bind to which port?: "); int portToBind = Int32.Parse(Console.ReadLine()); Incoming.Bind(new IPEndPoint(IPAddress.Any, portToBind)); Incoming.Listen(); Console.WriteLine(String.Format("Listening for clients on {0}...", Incoming.Socket.LocalEndPoint)); Console.ReadLine(); Outgoing = new NetworkPeer(); Outgoing.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true); Outgoing.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); Console.Write("Outgoing: Bind to which port?: "); Outgoing.Bind(new IPEndPoint(IPAddress.Any, portToBind)); Console.Write("Endpoint of your peer: "); var introducerEndpoint = Console.ReadLine().Parse(); Console.WriteLine(String.Format("Connecting to at {0}:{1}...", introducerEndpoint.Address, introducerEndpoint.Port)); Outgoing.Connect(introducerEndpoint.Address, introducerEndpoint.Port); Console.ReadLine(); var mre = new System.Threading.ManualResetEvent(false); mre.WaitOne(); }
public void AddCallback( Customer requestingCustomer, string callbackTargetUri, string callbackTargetDisplayName) { var request = new CallbackRequest( requestingCustomer, callbackTargetUri, callbackTargetDisplayName); System.Threading.ManualResetEvent callbackSetupWaitHandle = new System.Threading.ManualResetEvent(false); AsyncTaskSequenceSerial sequence = new AsyncTaskSequenceSerial(this); sequence.Name = "AddCallback"; sequence.SuccessCompletionReportHandlerDelegate = delegate(Exception exception) { callbackSetupWaitHandle.Set(); }; sequence.FailureCompletionReportHandlerDelegate = delegate(Exception exception) { request.Exception = exception; callbackSetupWaitHandle.Set(); }; lock (this.SyncRoot) { if (this.IsTerminatingTerminated) { throw new InvalidOperationException("AddCallback called when CallbackManager is terminating/terminated."); } this.AddRequest(request); AsyncTask startEndpointTask = new AsyncTask(this.StartupUserEndpoint, request); sequence.AddTask(startEndpointTask); AsyncTask startPresenceView = new AsyncTask(this.StartupPresenceView, request); sequence.AddTask(startPresenceView); } sequence.Start(); callbackSetupWaitHandle.WaitOne(); if (request.Exception != null) { this.RemoveRequest(request); throw request.Exception; } }
public void Scheduled_Task_With_NextRunningDate() { var id = Guid.NewGuid(); var nextDate = DateTime.Now.AddHours(1); var task = Scheduler.CreateScheduledTask <ParameterizedTask>("schedulednextrunningdate", new System.Collections.Generic.Dictionary <string, object>() { { "input", "test" } }) .NextRunningDate(() => nextDate); var mre = new System.Threading.ManualResetEvent(false); Scheduler.Add(task); task.Completed += (dic) => { mre.Set(); }; mre.WaitOne(); Check.That(task.NextRunningDate.Ticks).IsEqualTo(nextDate.Ticks); }
internal async Task <Connection> AskForConnectionAsync() { using (var closedEvent = new System.Threading.ManualResetEvent(false)) { var dialog = new ConnectionDialog(); dialog.Closed += (sender, e) => { closedEvent.Set(); }; dialog.Show(); await Task.Run(new Action(() => closedEvent.WaitOne())); if (dialog.Ok ?? false) { return(dialog.Connection); } else { return(null); } } }
private void GetScenarios(int scenarioId) { var service = new PrepareService(); var mre = new System.Threading.ManualResetEvent(false); ScenariosData data = null; Exception e = null; service.GetScenarios(scenarioId, d => { data = d; mre.Set(); }, ex => { e = ex; mre.Set(); }); mre.WaitOne(); // Pour l'instant vérifie qu'aucune exception n'a été levée AssertExt.IsExceptionNull(e); }
private void programRestartButton_Click(object sender, RoutedEventArgs e) { if (program != null) { program.Abort(); program = null; } lock (bios) { bios.Reset(); } LoadProgram(); cpu.Running = CPUStatus.Running; pauseEvent = new System.Threading.ManualResetEvent(true); program = new System.Threading.Thread(() => { cpu.ExecuteProgram(programPosition, pauseEvent); }); program.Start(); }
public static void Main(string[] args) { Console.Error.WriteLine("BlackLinks Development Host"); if (args.Length == 0) { Console.Error.WriteLine("BlackLinks Web Application path is required"); System.Environment.Exit(1); } string appDir = args[0]; if (!Directory.Exists(appDir)) { Console.Error.WriteLine("{0} is not a valid directory", appDir); System.Environment.Exit(2); } var app = GatewayHostManager.LoadApplication <GatewayHostManager> (appDir); Console.WriteLine("Development Server Ready"); var ev = new System.Threading.ManualResetEvent(false); ev.WaitOne(); }
void SubCategoriedForAdditionalPages(RssLink parentCategory, List <string> urls) { System.Threading.ManualResetEvent[] threadWaitHandles = new System.Threading.ManualResetEvent[urls.Count]; for (int i = 0; i < urls.Count; i++) { threadWaitHandles[i] = new System.Threading.ManualResetEvent(false); new System.Threading.Thread(delegate(object o) { int o_i = (int)o; string addDataPage = GetWebData(urls[o_i]); if (o_i > 0) { System.Threading.WaitHandle.WaitAny(new System.Threading.ManualResetEvent[] { threadWaitHandles[o_i - 1] }); } ParseSubCategories(parentCategory, addDataPage); threadWaitHandles[o_i].Set(); }) { IsBackground = true }.Start(i); } System.Threading.WaitHandle.WaitAll(threadWaitHandles); }
public async Task <DialogResult> ShowDialog(DialogViewModel viewModel) { var waitHandle = new System.Threading.ManualResetEvent(false); _dialogHost.DataContext = viewModel; viewModel.PropertyChanged += (s, e) => { if (e.PropertyName == nameof(DialogViewModel.Result)) { _dialogHost.DataContext = null; if (viewModel.Result != DialogResult.None) { waitHandle.Set(); } } }; return(await Task.Factory.StartNew(() => { waitHandle.WaitOne(); return viewModel.Result; })); }
private void ReleaseResources() { try { _CloseEvent.Close(); } catch { } try { _Event.Close(); } catch { } _CloseEvent = null; _Event = null; _Thread = null; Started = false; }
/// <summary> /// ダイアログを表示する /// </summary> /// <param name="owner"> /// ownerの中央にダイアログが表示される /// </param> /// <remarks> /// このメソッドは一回しか呼び出せません。 /// </remarks> public void Show(Form owner) { if (showed) { throw new Exception("ダイアログは一度表示されています。"); } showed = true; _canceled = false; startEvent = new System.Threading.ManualResetEvent(false); ownerForm = owner; //スレッドを作成 thread = new System.Threading.Thread( new System.Threading.ThreadStart(Run)); thread.IsBackground = true; this.thread.ApartmentState = System.Threading.ApartmentState.STA; thread.Start(); //フォームが表示されるまで待機する startEvent.WaitOne(); }
private void HandleConsoleMessage(ElasticsearchConsoleOut consoleOut, XplatManualResetEvent handle) { Console.WriteLine(consoleOut.Data); //no need to snoop for metadata if we already started if (!this._config.RunIntegrationTests || this.Started) { return; } if (consoleOut.Error && !this.Started && !string.IsNullOrWhiteSpace(consoleOut.Data)) { throw new Exception("Error out:" + consoleOut.Data); } string version; int? pid; int port; if (this.ProcessId == null && consoleOut.TryParseNodeInfo(out version, out pid)) { var startedVersion = new ElasticsearchVersion(version); this.ProcessId = pid; if (this.Version != startedVersion) { throw new Exception($"Booted elasticsearch is version {startedVersion} but the test config dictates {this.Version}"); } } else if (consoleOut.TryGetPortNumber(out port)) { this.Port = port; } else if (consoleOut.TryGetStartedConfirmation()) { this.Started = true; handle.Set(); } }
public void TestReceiveSmallMessage_XML() { //Setting up the ILogger moq var loggerMock = CreateLoggerMock(); Context context = new Context(loggerMock.Object); MockReceiveStep step = new MockReceiveStep(); step.Url = connectionUri.Uri.OriginalString; step.Encoding = "UTF-8"; step.Timeout = 30; //Colling Validate in order to start the step.Validate(context); //Setting up a manual reset event System.Threading.ManualResetEvent manualEvent = new System.Threading.ManualResetEvent(false); //here we queue up the step.Execute method in a separate thread as the execution model would actually be System.Threading.ThreadPool.QueueUserWorkItem((state) => { step.Execute(context); manualEvent.Set(); }); string xml = "<SomeTestMessage><Element1 attribute1=\"attributeValue\"></Element1><Element2>Some element content</Element2></SomeTestMessage>"; Message msg = GeneralTestHelper.CreateMessageWithBase64EncodedBody(xml, Encoding.UTF8); outboundHandler.Execute(msg, TimeSpan.FromSeconds(10)); //Waiting for the manual event to be set manualEvent.WaitOne(1000); loggerMock.Verify(l => l.LogData( It.Is <string>(s => !string.IsNullOrEmpty(s)), It.Is <string>(s => !string.IsNullOrEmpty(s))), Times.AtLeastOnce(), "The LogData message was not called"); }
public override Task <Result> Scan(MobileBarcodeScanningOptions options) { return(Task.Factory.StartNew(() => { try { var scanResultResetEvent = new System.Threading.ManualResetEvent(false); Result result = null; this.appController.InvokeOnMainThread(() => { viewController = new ZxingCameraViewController(options, this); viewController.BarCodeEvent += (BarCodeEventArgs e) => { viewController.DismissViewController(); result = e.BarcodeResult; scanResultResetEvent.Set(); }; viewController.Canceled += (sender, e) => { viewController.DismissViewController(); scanResultResetEvent.Set(); }; appController.PresentViewController(viewController, true, () => { }); }); scanResultResetEvent.WaitOne(); return result; } catch (Exception ex) { return null; } })); }
private void HandleConsoleMessage(ElasticsearchConsoleOut consoleOut, XplatManualResetEvent handle) { if (consoleOut.Error && !this.Started) { this.Fatal(handle, new Exception(consoleOut.Data)); return; } //no need to snoop for metadata if we already started if (!this._config.RunIntegrationTests || this.Started) { return; } string version; int?pid; int port; if (this.ProcessId == null && consoleOut.TryParseNodeInfo(out version, out pid)) { var startedVersion = new ElasticsearchVersion(version); this.ProcessId = pid; if (this.Version != startedVersion) { this.Fatal(handle, new Exception($"Booted elasticsearch is version {startedVersion} but the test config dictates {this.Version}")); } } else if (consoleOut.TryGetPortNumber(out port)) { this.Port = port; } else if (consoleOut.TryGetStartedConfirmation()) { var client = this.GetPrivateClient(null, false, this.Port); this.ValidatePlugins(client, handle); this.ValidateLicense(client, handle); this.WaitForClusterBootstrap(client, handle, alreadyRunningInstance: false); } }
/// <summary> /// 根据指定远程服务,获取本机使用的ip /// </summary> /// <param name="remoteIP"></param> /// <param name="remotePort"></param> /// <param name="timeout"></param> /// <returns></returns> public static string GetLocalUsedIpAddress(string remoteIP, int remotePort, int timeout = 3000) { string localIP = null; try { using (var maual = new System.Threading.ManualResetEvent(false)) { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { var asy = socket.BeginConnect(remoteIP, remotePort, (o) => { try { if (socket.Connected) { string[] arr = socket.LocalEndPoint.ToString().Split(':'); if (arr.Length == 2) { localIP = arr[0]; } } } catch { } try { maual.Set(); } catch { } }, maual); maual.WaitOne(timeout); socket.Close(); } } } catch { } return(localIP); }
public override Task <Result> Scan(MobileBarcodeScanningOptions options) { var task = Task.Factory.StartNew(() => { var waitScanResetEvent = new System.Threading.ManualResetEvent(false); var scanIntent = new Intent(lifecycleListener.Context, typeof(ZxingActivity)); scanIntent.AddFlags(ActivityFlags.NewTask); ZxingActivity.UseCustomOverlayView = this.UseCustomOverlay; ZxingActivity.CustomOverlayView = this.CustomOverlay; ZxingActivity.ScanningOptions = options; ZxingActivity.TopText = TopText; ZxingActivity.BottomText = BottomText; Result scanResult = null; ZxingActivity.OnCanceled += () => { waitScanResetEvent.Set(); }; ZxingActivity.OnScanCompleted += (Result result) => { scanResult = result; waitScanResetEvent.Set(); }; lifecycleListener.Context.StartActivity(scanIntent); waitScanResetEvent.WaitOne(); return(scanResult); }); return(task); }
/// <summary> /// Start to receive message /// </summary> public void Start() { lock (_LockObj) { if (!Started) { if (RestartTimes > 0 && _StartOnce) { return; } _CloseEvent = new System.Threading.ManualResetEvent(false); Closing = false; _Sema = new System.Threading.Semaphore(0, int.MaxValue); _Thread = new System.Threading.Thread(new System.Threading.ThreadStart(MessageProc)); _Thread.IsBackground = true; if (_UrgentQueue.Count > 0) { _Sema.Release(_UrgentQueue.Count); } if (_Queue.Count > 0) { _Sema.Release(_Queue.Count); } _Thread.Start(); RestartTimes++; Started = true; } } }
protected override IAsyncResult OnBeginAcceptChannel(TimeSpan timeout, AsyncCallback callback, object asyncState) { var wait = new System.Threading.ManualResetEvent(false); if (accept_channel_delegate == null) { accept_channel_delegate = new Func <TimeSpan, TChannel>(delegate(TimeSpan tout) { wait.WaitOne(); CurrentAsyncThread = System.Threading.Thread.CurrentThread; try { return(OnAcceptChannel(tout)); } finally { CurrentAsyncThread = null; CurrentAsyncResult = null; } }); } CurrentAsyncResult = accept_channel_delegate.BeginInvoke(timeout, callback, asyncState); wait.Set(); return(CurrentAsyncResult); }
public override Task <Result> Scan(MobileBarcodeScanningOptions options) { Console.WriteLine("ZXING MOBILE: Scan"); var waitScanResetEvent = new System.Threading.ManualResetEvent(false); var scanIntent = new Intent(this.Context, typeof(ZxingActivity)); ZxingActivity.UseCustomView = this.UseCustomOverlay; ZxingActivity.CustomOverlayView = this.CustomOverlay; ZxingActivity.ScanningOptions = options; ZxingActivity.TopText = TopText; ZxingActivity.BottomText = BottomText; var task = Task.Factory.StartNew(() => { Result scanResult = null; ZxingActivity.OnCanceled += () => { waitScanResetEvent.Set(); }; ZxingActivity.OnScanCompleted += (Result result) => { scanResult = result; waitScanResetEvent.Set(); }; this.Context.RunOnUiThread(() => this.Context.StartActivity(scanIntent)); waitScanResetEvent.WaitOne(); return(scanResult); }); return(task); }
public static T RunInUnityThreadAndWait <T>(Func <T> func) { if (func != null) { if (ThreadLocalObj.GetThreadId() == ThreadSafeValues.UnityThreadID) { return(func()); } else { T rv = default(T); System.Threading.ManualResetEvent waithandle = new System.Threading.ManualResetEvent(false); AddEvent(() => { rv = func(); waithandle.Set(); }); waithandle.WaitOne(); waithandle.Close(); return(rv); } } return(default(T)); }
public void GetProjectsTest() { SampleData.ClearDatabaseThenImportDefaultProject(); var service = new PrepareService(); var mre = new System.Threading.ManualResetEvent(false); ProjectsData data = null; Exception e = null; service.GetProjects(d => { data = d; mre.Set(); }, ex => { e = ex; mre.Set(); }); mre.WaitOne(); // Pour l'instant vérifie qu'aucune exception n'a été levée AssertExt.IsExceptionNull(e); }
public void LogCallContext_ContextClearedAfterPops() { using (var signal = new System.Threading.ManualResetEvent(false)) { using (var prop = LogCallContext.PushProperty("Test Prop 1", Guid.NewGuid())) { using (var prop2 = LogCallContext.PushProperty("Test Prop 2", Guid.NewGuid())) { bool assertsPassedOnOtherThread = false; System.Threading.ThreadPool.QueueUserWorkItem((reserved) => { var firstProp = LogCallContext.CurrentProperties.First(); Assert.AreEqual("Test Prop 2", firstProp.Key); var lastProp = LogCallContext.CurrentProperties.Last(); Assert.AreEqual("Test Prop 1", lastProp.Key); assertsPassedOnOtherThread = true; signal.Set(); }); signal.WaitOne(); Assert.IsTrue(assertsPassedOnOtherThread); } } signal.Reset(); var contextWasEmptyOnOtherThread = false; System.Threading.ThreadPool.QueueUserWorkItem((reserved) => { contextWasEmptyOnOtherThread = !LogCallContext.CurrentProperties.Any(); signal.Set(); }); signal.WaitOne(); Assert.IsTrue(contextWasEmptyOnOtherThread); } }
public void Connect(string hostname, int port) { if (ConnectTimeout > TimeSpan.Zero) { // https://forum.unity3d.com/threads/best-http-released.200006/page-37#post-3150972 System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false); IAsyncResult result = Dns.BeginGetHostAddresses(hostname, (res) => mre.Set(), null); bool success = mre.WaitOne(ConnectTimeout); if (success) { IPAddress[] addresses = Dns.EndGetHostAddresses(result); Connect(addresses, port); } else { throw new TimeoutException("DNS resolve timed out!"); } } else { IPAddress[] addresses = Dns.GetHostAddresses(hostname); Connect(addresses, port); } }
public static void Main() { allDone = new ManualResetEvent(false); // Create an instance of the RequestState class. RequestState myRequestState = new RequestState(); // Begin an asynchronous request for information like host name, IP addresses, or // aliases for specified the specified URI. IAsyncResult asyncResult = Dns.BeginResolve("www.contoso.com", new AsyncCallback(RespCallback), myRequestState); // Wait until asynchronous call completes. allDone.WaitOne(); Console.WriteLine("Host name : " + myRequestState.host.HostName); Console.WriteLine("\nIP address list : "); for (int index = 0; index < myRequestState.host.AddressList.Length; index++) { Console.WriteLine(myRequestState.host.AddressList[index]); } Console.WriteLine("\nAliases : "); for (int index = 0; index < myRequestState.host.Aliases.Length; index++) { Console.WriteLine(myRequestState.host.Aliases[index]); } }
protected override void OnElementChanged(ElementChangedEventArgs <Xamarin.Forms.WebView> e) { base.OnElementChanged(e); var webView = e.NewElement as AdvWebView; if (webView != null) { webView.EvaluateJavascript = async(js) => { var reset = new System.Threading.ManualResetEvent(false); var response = string.Empty; Device.BeginInvokeOnMainThread(() => { Control?.EvaluateJavascript(js, new JavascriptCallback((r) => { response = r; reset.Set(); })); }); await Task.Run(() => { reset.WaitOne(); }); return(response); } } ; } }
protected override void Main() { var endPoint = new IPEndPoint(IPAddress.Loopback, 15005); IObservable <int> clientQuery = Observable.Using( () => new TcpClient(), client => from _ in client.ConnectObservable(endPoint.Address, endPoint.Port) let socket = client.Client let message = Encoding.UTF8.GetBytes(Text.Rock + Text.Scissors + Text.Paper) from __ in socket.SendUntilCompleted(message, 0, message.Length, SocketFlags.None) select message.Length); IObservable <string> serverQuery = from client in ObservableTcpListener.Start(endPoint) .Synchronize() .Take(1) .Do(_ => { TraceLine(Text.ServerReceivedRequest); PressAnyKeyToContinue(); }) let stream = new NetworkStream(client.Client, ownsSocket: false) from buffer in Observable.Using( () => client, _ => stream.ReadToEndObservable().SelectMany(b => b).ToArray()) let message = Encoding.UTF8.GetString(buffer) select message; using (var responded = new System.Threading.ManualResetEvent(false)) using (serverQuery.Finally(() => responded.Set()).Subscribe(ConsoleOutput(Text.Server))) using (clientQuery.Subscribe(ConsoleOutputFormat(Text.Client, Text.SentBytesFormat))) { responded.WaitOne(); } }
public Task <ZXing.Result> Scan(MobileBarcodeScanningOptions options) { var task = Task.Factory.StartNew(() => { var waitScanResetEvent = new System.Threading.ManualResetEvent(false); var scanIntent = new Intent(Context, typeof(PortraitZxingActivity)); scanIntent.AddFlags(ActivityFlags.NewTask); ZxingActivity.UseCustomOverlayView = true; ZxingActivity.CustomOverlayView = View.Inflate(Context, Resource.Layout.overlay_scan_view, null); ZxingActivity.ScanningOptions = options; ZxingActivity.ScanContinuously = false; ZxingActivity.TopText = ""; ZxingActivity.BottomText = ""; ZXing.Result scanResult = null; ZxingActivity.CanceledHandler = () => waitScanResetEvent.Set(); ZxingActivity.ScanCompletedHandler = (ZXing.Result result) => { scanResult = result; waitScanResetEvent.Set(); }; Context.StartActivity(scanIntent); waitScanResetEvent.WaitOne(); return(scanResult); }); return(task); }
public Client(Game game, System.ComponentModel.ISynchronizeInvoke synchronize) : base(game, new Version(CLIENTVERSION_MAJOR, CLIENTVERSION_MINOR), synchronize) { try { string s = System.Configuration.ConfigurationManager.AppSettings["Network.Port"]; if (s == null) { throw new System.Configuration.ConfigurationErrorsException("No key named 'Network.Port' in the application configuration."); } Port = int.Parse(s); s = System.Configuration.ConfigurationManager.AppSettings["Network.WaitForServers"]; if (s == null) { throw new System.Configuration.ConfigurationErrorsException("No key named 'Network.WaitForServers' in the application configuration."); } WaitForServers = int.Parse(s); ManuelResetEvent = new System.Threading.ManualResetEvent(true); SynchronizeRoot = Singleton.Instance; } catch (System.Exception ex) { throw ex; } }