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 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(); }
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 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 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; })); }
static void Main() { System.Threading.ManualResetEvent close = new System.Threading.ManualResetEvent(false); SystemEvents.SessionEnding += (object sender, SessionEndingEventArgs e) => close.Set(); BaseClass(); close.WaitOne(); }
public void Wait(TimeSpan timeout) { try { if (!(_DataArrivedSignal?.WaitOne(timeout) ?? false)) { var te = new TimeoutException("No response from NTP server."); throw new NtpNetworkException(te.Message, (int)SocketErrorStatus.OperationAborted, te); } } catch (ObjectDisposedException) { } }
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 (); }
public void NLogTargetFlushesTelemetryClient() { var aiLogger = this.CreateTargetWithGivenInstrumentationKey(); var flushEvent = new System.Threading.ManualResetEvent(false); Exception flushException = null; NLog.Common.AsyncContinuation asyncContinuation = (ex) => { flushException = ex; flushEvent.Set(); }; aiLogger.Factory.Flush(asyncContinuation, 5000); Assert.IsTrue(flushEvent.WaitOne(5000)); Assert.IsNotNull(flushException); Assert.AreEqual("Flush called", flushException.Message); }
public void Wait(int waitInterval, Action whileWaiting) { var mre = new System.Threading.ManualResetEvent(false); while (this.IsActive) { mre.WaitOne(100); if (whileWaiting != null) { whileWaiting(); } } }
/// <summary> /// Helper method that the current running task can call to obtain the current state /// </summary> public TaskControlState TaskControlRendevouz() { // If we are paused, go into pause mode m_pauseEvent.WaitOne(); // If we are aborted, throw exception if (m_controlState == TaskControlState.Abort) { System.Threading.Thread.CurrentThread.Abort(); } return(m_controlState); }
/// <summary> /// Executes the tasks and waits for the result. /// </summary> /// <returns>The result of the operation.</returns> public T ExecuteAndWait() { TraceHelper.WriteLine("Task, ExecuteAndWait"); // Potential optimization: Make sure that synchronous results are not creating events using (System.Threading.ManualResetEvent evt = new System.Threading.ManualResetEvent(false)) { this.ExecuteStep(() => { evt.Set(); }); evt.WaitOne(); } return(this.Result); }
static T WaitCore <T>(IObservable <T> source, bool throwOnEmpty, TimeSpan timeout) { if (source == null) { throw new ArgumentNullException("source"); } var semaphore = new System.Threading.ManualResetEvent(false); var seenValue = false; var value = default(T); var ex = default(Exception); using (source.Subscribe( onNext: x => { seenValue = true; value = x; }, onError: x => { ex = x; semaphore.Set(); }, onCompleted: () => semaphore.Set())) { var waitComplete = (timeout == InfiniteTimeSpan) ? semaphore.WaitOne() : semaphore.WaitOne(timeout); if (!waitComplete) { throw new TimeoutException("OnCompleted not fired."); } } if (ex != null) { throw ex; } if (throwOnEmpty && !seenValue) { throw new InvalidOperationException("No Elements."); } return(value); }
public void BlockUntilUnloadIsSafe() { if (isUnloading) { throw new InvalidOperationException("PluginManager is already unloading."); } isUnloading = true; unloadCount = ApiExecutors.Count + AppExecutors.Count; ApiExecutors.ForEach(x => x.SetZeroUseNotification(decreaseUnloadCount)); AppExecutors.ForEach(x => x.SetZeroUseNotification(decreaseUnloadCount)); unloadSignal.WaitOne(); GC.WaitForPendingFinalizers(); }
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 ( ); } ); }
System.Runtime.Remoting.Messaging.IMessage DoInvoke(System.Runtime.Remoting.Messaging.IMessage inputMessage) { var inmsg = (System.Runtime.Remoting.Messaging.IMethodCallMessage)inputMessage; var od = channel.Contract.Operations.FirstOrDefault(o => inmsg.MethodBase.Equals(o.SyncMethod) || inmsg.MethodBase.Equals(o.BeginMethod) || inmsg.MethodBase.Equals(o.EndMethod)); if (od == null) { var ret = inmsg.MethodBase.Invoke(channel, inmsg.InArgs); return(new System.Runtime.Remoting.Messaging.ReturnMessage(ret, null, 0, null, inmsg)); } else { object[] pl; System.Reflection.MethodBase method = null; List <object> outArgs = null; object ret; if (inmsg.MethodBase.Equals(od.SyncMethod)) { pl = new object[inmsg.MethodBase.GetParameters().Length]; Array.Copy(inmsg.Args, pl, inmsg.ArgCount); ret = channel.Process(inmsg.MethodBase, od.Name, pl, System.ServiceModel.OperationContext.Current); method = od.SyncMethod; } else if (inmsg.MethodBase.Equals(od.BeginMethod)) { pl = new object[inmsg.ArgCount - 2]; Array.Copy(inmsg.Args, 0, pl, 0, pl.Length); ret = channel.BeginProcess(inmsg.MethodBase, od.Name, pl, (AsyncCallback)inmsg.Args[inmsg.ArgCount - 2], inmsg.Args[inmsg.ArgCount - 1]); saved_params[ret] = pl; wait.Set(); } else { var result = (IAsyncResult)inmsg.InArgs[0]; wait.WaitOne(); pl = saved_params[result]; wait.Reset(); saved_params.Remove(result); ret = channel.EndProcess(inmsg.MethodBase, od.Name, pl, result); method = od.BeginMethod; } if (method != null && method.GetParameters().Any(pi => pi.IsOut || pi.ParameterType.IsByRef)) { return(new System.Runtime.Remoting.Messaging.ReturnMessage(ret, pl, pl.Length, null, inmsg)); } else { return(new System.Runtime.Remoting.Messaging.ReturnMessage(ret, outArgs != null ? outArgs.ToArray() : null, outArgs != null ? outArgs.Count : 0, null, inmsg)); } } }
void StartRenderLoop() { // If the render loop is already running then do not start another thread. if (_renderLoopWorker != null && _renderLoopWorker.Status == Windows.Foundation.AsyncStatus.Started) { return; } // Create a task for rendering that will be run on a background thread. var workItemHandler = new Windows.System.Threading.WorkItemHandler((Windows.Foundation.IAsyncAction action) => { lock (_renderSurfaceLock) { _eglContext.MakeCurrent(_renderSurface); int oldPanelWidth = -1; int oldPanelHeight = -1; while (action.Status == Windows.Foundation.AsyncStatus.Started) { int panelWidth = 0; int panelHeight = 0; GetSwapChainPanelSize(out panelWidth, out panelHeight); if (panelWidth != oldPanelWidth || panelHeight != oldPanelHeight) { _baseMapView.OnSurfaceChanged(panelWidth, panelHeight); oldPanelWidth = panelWidth; oldPanelHeight = panelHeight; } _baseMapView.OnDrawFrame(); // The call to eglSwapBuffers might not be successful (i.e. due to Device Lost) // If the call fails, then we must reinitialize EGL and the GL resources. if (!_eglContext.SwapBuffers(_renderSurface)) { // XAML objects like the SwapChainPanel must only be manipulated on the UI thread. var worker = _swapChainPanel.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() => { RecoverFromLostDevice(); })); worker.Close(); return; } _swapChainEvent.WaitOne(); _swapChainEvent.Reset(); } } }); // Run task on a dedicated high priority background thread. _renderLoopWorker = Windows.System.Threading.ThreadPool.RunAsync(workItemHandler, Windows.System.Threading.WorkItemPriority.Normal, Windows.System.Threading.WorkItemOptions.TimeSliced); }
private void GetPackets() { while (NotCancelled) { if (ReadBufferContainsData) { _buffer.AddRange(_context.Communicator.ReadAllBytes()); } else if (_watchDogWaitHandle.WaitOne(0)) { SendNAK(); Reset(); ResetWatchDog(); continue; } else { continue; } PauseAndResetWatchDog(); CheckForCancellation(); if (EOTwasReceived) { SendACK(); return; } if (BufferLengthIsTooShort) { continue; } if (BufferContainsValidPacket) { SendACK(); if (PacketIsNotDuplicate) { ExtractDataFromBuffer(); FirePacketReceivedEvent(); } } else { SendNAK(); } Reset(); } }
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 async Task SerializeTransactionExceptionTest() { // Accéder à une même donnée ds une session Serializable génere une SerializeTransactionException var store = await StoreBuilder.New().CreateAsync(); await store.Schemas.New <TestDomainDefinition>().Set(Setting.MaxTimeBeforeDeadlockInMs, 100).CreateAsync(); var domain = await store.DomainModels.New().CreateAsync("Test"); var gate = new System.Threading.ManualResetEvent(false); var factory = new TaskFactory(); var t1 = factory.StartNew(() => { using (var s = store.BeginSession(new SessionConfiguration { IsolationLevel = SessionIsolationLevel.Serializable })) { s.AcquireLock(LockType.Exclusive, "a"); gate.Set(); Sleep(200); s.AcceptChanges(); } }); var t2 = factory.StartNew(() => { using (var s = store.BeginSession(new SessionConfiguration { IsolationLevel = SessionIsolationLevel.Serializable })) { gate.WaitOne(); // Récupération du lock mais la transaction t1 à fait un commit // on obtient une SerializeTransactionException Debug.WriteLine("T2 acquire"); s.AcquireLock(LockType.Exclusive, "a"); } }); try { Task.WaitAll(t1, t2); throw new Exception("Inconclusive"); } catch (AggregateException ex) { Assert.IsType <SerializableTransactionException>(ex.InnerException); } }
//[Test] public void ChangeEventTest() { var sawChange = new System.Threading.ManualResetEvent(false); Clipboard.ClipboardUpdate += OnUpdate; System.Threading.Thread.SpinWait(1000); WFClipboard.SetText("Hello"); //using var cb = new Clipboard(); //cb.SetText("Hello"); Assert.IsTrue(sawChange.WaitOne(5000)); Clipboard.ClipboardUpdate -= OnUpdate; void OnUpdate(object sender, EventArgs e) => sawChange.Set(); }
public static void Main(string[] args) { //Démarrer Bot la première fois, avant le Timer AlgoTrading.Bot(); //Debut Timer Timer timer = new Timer(); timer.Interval = General.timerInterval * 60 * 1000; // Convertir ms en minutes timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.Enabled = true; timerFired.WaitOne(); }
public static void Main(string[] args) { //Start Bot the first time, before timer Algorithm.Bot(); //Start Timer Timer timer = new Timer(); timer.Interval = Globals.timerInterval * 60 * 1000; // converts ms to minutes timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.Enabled = true; timerFired.WaitOne(); //https://stackoverflow.com/questions/34958759/timer-does-not-fire-before-application-ends-in-c-sharp?rq=1 }
public void TestIDLE() { var mre = new System.Threading.ManualResetEvent(false); using (var imap = GetClient <ImapClient>()) { imap.SelectMailbox("inbox"); imap.NewMessage += imap_NewMessage; while (!mre.WaitOne(5000)) //low for the sake of testing; typical timeout is 30 minutes { imap.Noop(); } } }
public void Connect(IPEndPoint remoteEP) { try { // Third version, works in WebPlayer System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false); IAsyncResult result = client.BeginConnect(remoteEP, (res) => mre.Set(), null); active = mre.WaitOne(ConnectTimeout); if (active) { client.EndConnect(result); } else { try { client.Close(); } catch { } throw new TimeoutException("Connection timed out!"); } // Second version with timeout, in WebPlayer can't connect: // Attempt to access a private/protected method failed. at System.Security.SecurityManager.ThrowException (System.Exception ex) [0x00000] in <filename unknown>:0 /*IAsyncResult result = client.BeginConnect(remoteEP, null, null); * Active = result.AsyncWaitHandle.WaitOne(ConnectTimeout, true); * if (active) * { * client.EndConnect(result); * } * else * { * client.Close(); * //throw new SocketException(10060); * throw new TimeoutException("Connection timed out!"); * }*/ // First(old) version, no timeout /*client.Connect(remoteEP); * active = true;*/ } finally { CheckDisposed(); } }
public void AcceptLoop() { System.IAsyncResult asyncResult; serverSock.Blocking = false; while (ServerState) { newConnection.Reset(); asyncResult = serverSock.BeginAccept(new AsyncCallback(ConectionRecivedCallBack), serverSock); newConnection.WaitOne(); } return; }
public void Start(string[] settings) { if (!this._config.RunIntegrationTests || this.Started) { return; } lock (_lock) { if (!this._config.RunIntegrationTests || this.Started) { return; } this.FreeResources(); if (UseAlreadyRunningInstance()) { this.Started = true; return; } var timeout = TimeSpan.FromMinutes(1); var handle = new XplatManualResetEvent(false); var booted = false; var process = new ObservableProcess(this.FileSystem.Binary, settings); this._composite = new CompositeDisposable(process); Console.WriteLine($"Starting: {process.Binary} {process.Arguments}"); try { var subscription = Observable.Using(() => process, p => p.Start()) .Select(c => new ElasticsearchConsoleOut(this._config.ElasticsearchVersion, c.Error, c.Data)) .Subscribe(s => this.HandleConsoleMessage(s, handle), e => { throw e; }, () => handle.Set()); this._composite.Add(subscription); if (!handle.WaitOne(timeout, true)) { throw new Exception($"Could not start elasticsearch within {timeout}"); } booted = true; } finally { if (!booted) { this.FreeResources(); } } } }
public bool Wait(TimeSpan timeout, out T value) { var isSafeToClose = false; try { if (timeout == TimeSpan.MaxValue) { waitEvent.WaitOne(); } else if (!waitEvent.WaitOne(timeout, false)) { if (inputQueue.RemoveReader(this)) { value = default(T); isSafeToClose = true; return(false); } else { waitEvent.WaitOne(); } } isSafeToClose = true; } finally { if (isSafeToClose) { waitEvent.Close(); } } value = item; return(true); }
/// <summary> /// Blocks the current thread until the <see cref="Gate">Gate</see> is opened. /// </summary> /// <param name="timeoutPeriod"> /// An enumeration indicating the number of milliseconds to wait for the gate to open, or a positive /// manually-specified value.</param> /// <returns> /// True if the gate was opened, or False if the current thread /// waited for the specified time and the gate was not opened. /// </returns> public bool WaitUntilOpen(GateTimeout timeoutPeriod) { int timeout; timeout = (int)timeoutPeriod; switch (timeoutPeriod) { case GateTimeout.Infinite: timeout = GateTimeoutInfinite; break; case GateTimeout.Long: timeout = GateTimeoutLong; break; case GateTimeout.Medium: timeout = GateTimeoutMedium; break; case GateTimeout.Short: timeout = GateTimeoutShort; break; default: timeout = Math.Max(GateTimeoutMinimum, timeout); timeout = Math.Min(GateTimeoutMaximium, timeout); break; } return(cgEvent.WaitOne(timeout, false)); }
/// <summary> /// Starts an instance of ArcGIS Pro Application /// </summary> public static async void StartApplication() { var evt = new System.Threading.ManualResetEvent(false); System.Threading.Tasks.Task ready = null; var uiThread = new System.Threading.Thread(() => { try { Application = new ProApp(); ready = Application.TestModeInitializeAsync(); evt.Set(); } catch (XamlParseException) { throw new FatalArcGISException("Pro is not licensed"); } catch (Exception ex) { throw ex; } finally { evt.Set(); } System.Windows.Threading.Dispatcher.Run(); }); uiThread.TrySetApartmentState(System.Threading.ApartmentState.STA); uiThread.Name = "Test UI Thread"; uiThread.IsBackground = true; uiThread.Start(); evt.WaitOne(); // Task ready to wait on. if (ready != null) { try { await ready; } catch (Exception ex) { throw ex; } } }
public void TestReceiveSmallMessages_Debatch50_XML() { //Setting up the ILogger moq var loggerMock = TestMockReceiveStep.CreateLoggerMock(); Context context = new Context(loggerMock.Object); MockRequestResponseStep step = new MockRequestResponseStep(); step.Url = connectionUri.Uri.OriginalString; step.Encoding = "UTF-8"; step.ResponsePath = "TestResponse.xml"; step.Timeout = 30; step.DebatchedMessageCount = 50; //Calling 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(); }); var responseMessageList = new List <Message>(3); string xml = "<SomeTestMessage><Element1 attribute1=\"attributeValue\"></Element1><Element2>Some element content</Element2></SomeTestMessage>"; for (int i = 0; i < 50; i++) { Message msg = GeneralTestHelper.CreateMessageWithBase64EncodedBody(xml, Encoding.UTF8); msg.Properties.Add("http://schemas.microsoft.com/BizTalk/2003/system-properties#IsSolicitResponse", true); var responseMsg = outboundHandler.Execute(msg, TimeSpan.FromSeconds(10)); responseMessageList.Add(responseMsg); } //Waiting for the manual event to be set manualEvent.WaitOne(3000); Assert.AreEqual(50, responseMessageList.Count, "The number of response messages is incorrect."); loggerMock.Verify(l => l.LogData( It.Is <string>(s => !string.IsNullOrEmpty(s)), It.Is <string>(s => !string.IsNullOrEmpty(s))), Times.Exactly(100), "The LogData method was not called"); }
protected override void OnDownloaderFinished(HttpDownloader downloader) { var amz_downloader = (AmzMp3Downloader)downloader; var track = amz_downloader.Track; bool last_file = (TotalDownloadCount == 1); if (downloader.State.Success) { switch (amz_downloader.FileExtension) { case "mp3": case "wmv": case "mp4": if (last_file) { import_event.Reset(); } Log.InformationFormat("Finished downloading \"{0}\" by {1}; adding to import queue", track.Title, track.Creator); try { import_manager.Enqueue(amz_downloader.LocalPath); } catch (Exception e) { Log.Error("Trying to queue amz file", e); } break; default: non_mp3_queue.Enqueue(amz_downloader); break; } } // This is the final download; ensure the non-MP3 items have their metadata // updated and are imported, and wait until the import_manager is done before // calling base.OnDownloaderFinished since that will make the Job finished which will // mean all references to the manager are gone and it may be garbage collected. if (last_file) { Log.InformationFormat("Amazon downloader: waiting for last file to be imported"); TryToFixNonMp3Metadata(); import_event.WaitOne(); Log.InformationFormat("Amazon downloader: last file imported; finishing"); } base.OnDownloaderFinished(downloader); //Log.InformationFormat ("Finished downloading \"{0}\" by {1}; Success? {2} File: {3}", track.Title, track.Creator, //downloader.State.Success, amz_downloader.LocalPath); }
// 서버 실행 public void StartListening() { // bind and listen server.Bind(localEndPoint); server.Listen(100); Console.WriteLine("채팅 서버를 시작합니다."); while (true) // 서버가 닫힐 때까지 접속자를 계속 받는다. { allDone.Reset(); // 콜백의 파라미터로 넘겨줄 객체는 server(마지막 파라미터) server.BeginAccept(new AsyncCallback(AcceptCallback), server); allDone.WaitOne(); // 접속이 있을때까지 대기 } }
public Task <ReceivedUdpData> ReceiveAsync() { return(Task.Run <ReceivedUdpData>(() => { ReceivedUdpData data = null; while (!_ReceivedData.TryDequeue(out data)) { _DataAvailableSignal.WaitOne(); } _DataAvailableSignal.Reset(); return data; })); }
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 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); } }
/// <summary> /// /// </summary> /// <param name="timeout">超时时间</param> /// <returns></returns> public bool Wait(long timeout) { _timeout = timeout; _procHandle.BeginInvoke(null, null, null); //异步执行 bool flag = _event.WaitOne((int)timeout, false); //如果在规定时间内没等到通知则为 false if (!flag) { //触发超时事件 _timeoutHandle?.Invoke(null); } Dispose(); return(flag); }
public override void Send(System.Threading.SendOrPostCallback callback, object state) { if (SynchronizationContext.Current == mainThread) { callback(state); } else { using (var manualReset = new System.Threading.ManualResetEvent(false)) { _requests.Add(new Request(callback, state, manualReset)); manualReset.WaitOne(); } } }
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 IObservable <ElasticsearchConsoleOut> Start(string[] additionalSettings = null) { if (!this._config.RunIntegrationTests) { return(Observable.Empty <ElasticsearchConsoleOut>()); } this.Stop(); var settingMarker = this.Version.Major >= 5 ? "-E " : "-D"; var settings = DefaultNodeSettings .Concat(additionalSettings ?? Enumerable.Empty <string>()) .Select(s => $"{settingMarker}{s}") .ToList(); this.FileSystem.BeforeStart(settings); var handle = new XplatManualResetEvent(false); var alreadyRunning = UseAlreadyRunningInstance(handle); if (alreadyRunning != null) { return(alreadyRunning); } this._process = new ObservableProcess(this.FileSystem.Binary, settings.ToArray()); var observable = Observable.Using(() => this._process, process => process.Start()) .Select(c => new ElasticsearchConsoleOut(c.Error, c.Data)); Console.WriteLine($"Starting: {_process.Binary} {_process.Arguments}"); this._processListener = observable .Subscribe(s => this.HandleConsoleMessage(s, handle), (e) => this.Stop(), () => { }); if (!handle.WaitOne(HandleTimeout, true)) { this.Stop(); throw new Exception($"Could not start elasticsearch within {HandleTimeout}"); } if (this.Exception != null) { throw this.Exception; } return(observable); }
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(); }
/// <summary> /// Call to wait for an event that is newer than the current known event /// </summary> /// <param name="eventId">The last known event id</param> /// <param name="milliseconds">The number of milliseconds to block</param> /// <returns>The current event id</returns> public long Wait(long eventId, int milliseconds) { System.Threading.ManualResetEvent mre; lock (m_lock) { //If a newer event has already occured, return immediately if (eventId != m_eventNo) return m_eventNo; //Otherwise register this thread as waiting mre = new System.Threading.ManualResetEvent(false); m_waitQueue.Enqueue(mre); } //Wait until we are signalled or the time has elapsed mre.WaitOne(milliseconds, false); return m_eventNo; }
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; } }
public bool GetIsCertificateTrusted (string uri, string certificateFingerprint) { bool value; if (!TrustedCertificates.TryGetValue (certificateFingerprint, out value)) { using (var handle = new System.Threading.ManualResetEvent (false)) { Gtk.Application.Invoke (delegate { value = MessageService.AskQuestion ( "Untrusted HTTP certificate detected", string.Format ("Do you want to temporarily trust this certificate in order to" + " connect to the server at {0}?", uri), AlertButton.Yes, AlertButton.No) == AlertButton.Yes; TrustedCertificates [certificateFingerprint] = value; handle.Set (); }); handle.WaitOne (); } } return value; }
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(); }
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.ScanContinuously = false; ZxingActivity.TopText = TopText; ZxingActivity.BottomText = BottomText; Result scanResult = null; ZxingActivity.CanceledHandler = () => { waitScanResetEvent.Set(); }; ZxingActivity.ScanCompletedHandler = (Result result) => { scanResult = result; waitScanResetEvent.Set(); }; lifecycleListener.Context.StartActivity(scanIntent); waitScanResetEvent.WaitOne(); return scanResult; }); return task; }
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 void ManagerFileWatcher() { // PluginManager should be able to reload plugins that exist on file when the // plugin's file is changed. System.Threading.ManualResetEvent reset = new System.Threading.ManualResetEvent(false); IronPlugins.PluginManager mgr = new IronPlugins.PluginManager(); mgr.PluginReloaded += new IronPlugins.PluginManager.PluginReloadedEventHandler( delegate(object sender, IronPlugins.PluginReloadEventArgs args) { reset.Set(); } ); IronPlugins.Plugin.FilePlugin filePlugin = new IronPlugins.Plugin.FilePlugin("file_manager_test.py"); mgr.AddPlugin(filePlugin); // Write a new attribute to the file. This imitates someone changing a plugin file. using (System.IO.TextWriter writer = new System.IO.StreamWriter("file_manager_test.py")) { writer.Write("new_attribute = 82"); } reset.WaitOne(); // Wait for the plugin to be reloaded Assert.IsTrue(filePlugin.Invoke("new_attribute") == 82); // Check if the new attribute exists mgr.Dispose(); }
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 void whenProductIsPurchasedAndItCostsLessThanInsertedMakeChange() { // Special arrangements here as we need to ensure events are complete // before enforcing our assertions System.Threading.ManualResetEvent eventProduct = new System.Threading.ManualResetEvent(false); bool wasProductRaised = false; // Insert coins this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfQuarter, InsertableCoinSizes.SizeOfQuarter); this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfQuarter, InsertableCoinSizes.SizeOfQuarter); this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfQuarter, InsertableCoinSizes.SizeOfQuarter); this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfDime, InsertableCoinSizes.SizeOfDime); this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfNickel, InsertableCoinSizes.SizeOfNickel); // Tricky, after product is dispensed, begin dispensing change, so we need to know when event happens this._vendingMachine.ProductSelectorButtons.OnSelectedProductChanged += delegate (object sender, ProductForSale e) { wasProductRaised = true; eventProduct.Set(); }; // This will start the events firing this._vendingMachine.ProductSelectorButtons.SelectedProduct = ProductForSale.Chips; eventProduct.WaitOne(5000, false); Assert.IsTrue(wasProductRaised); // Ensures no false positive from a timeout // Check for our left over change Assert.AreEqual(1, this._vendingMachine.CoinReturn[InsertedCoin.Quarter]); Assert.AreEqual(1, this._vendingMachine.CoinReturn[InsertedCoin.Dime]); Assert.AreEqual(1, this._vendingMachine.CoinReturn[InsertedCoin.Nickel]); }
/// <summary> /// Start converting the specified track. For a track in an audio CD playlist, this /// is equivalent to importing the song. Use CurrentEncoder to set the current /// encoder before converting /// </summary> /// <param name="path"></param> /// <returns></returns> public Track ConvertTrack2(Track convertible) { return Invoke((Func<Track>)delegate { System.Threading.ManualResetEvent reset = new System.Threading.ManualResetEvent(false); object refTrack = convertible.AsInternal; iTunesConvertOperationStatus status = itunes.ConvertTrack2(ref refTrack); status.OnConvertOperationCompleteEvent += delegate { // this anonymous callback delegate signals the scanner // thread to continue... reset.Set(); }; // wait for the current conversion to complete, otherwise iTunes // raises an exception when concurrent conversions are requested reset.WaitOne(); reset.Reset(); reset = null; Track track = null; try { if (status.Tracks.Count > 0) { track = new Track(status.Tracks[1]); } } catch (NullReferenceException exc) { // NullRefException can occur when iTunes displays the "protected" dialog. // We cannot test if status.Tracks is even null because that alone will // throw a COMException throw new ProtectedException( "Possible protection fault in Controller.ConvertTrack2", exc); } finally { Release(status); } return track; }); }
private void WaitForGameState(EngineGameState target) { // Immediately returns if the engine is in the target state, // or if the engine has previously crashed. lock (_SyncRoot) { if (_IsInCrash) { return; } } try { CheckStateIs(target, null); // If we get here, it means that the engine is in the target state. return; } catch (InvalidOperationException) { // The engine is performing a concurrent operation. // Let's keep on going. } // Sets up a manual reset event that is set when the engine state // changes to the target game state. System.Threading.ManualResetEvent resetEvent = new System.Threading.ManualResetEvent(false); PropertyChangedEventHandler handler = new PropertyChangedEventHandler((o, e) => { if (e.PropertyName == "GameState") { try { CheckStateIs(target, null); // The engine is not in a concurrent game operation. // Let's signal the event. resetEvent.Set(); } catch (InvalidOperationException) { // The engine is performing a concurrent operation. // Let's wait some more. return; } } }); PropertyChanged += handler; // Waits on the event. resetEvent.WaitOne(); // Removes the handler. PropertyChanged -= handler; }
public void DeviceLocator_Notifications_RaisesDeviceUnavailableWithMatchedNotificationFilter() { var publishedDevice = CreateDeviceTree(); var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var discoveredDevices = new List<DiscoveredSsdpDevice>(); using (var eventSignal = new System.Threading.ManualResetEvent(false)) { deviceLocator.DeviceUnavailable += (sender, args) => { discoveredDevices.Add(args.DiscoveredDevice); eventSignal.Set(); }; deviceLocator.NotificationFilter = publishedDevice.Devices.First().Udn; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockByeByeNotification(publishedDevice)); server.WaitForMessageToProcess(10000); server.MockReceiveBroadcast(GetMockByeByeNotification(publishedDevice.Devices.First().Devices.First())); server.WaitForMessageToProcess(10000); server.MockReceiveBroadcast(GetMockByeByeNotification(publishedDevice.Devices.First())); server.WaitForMessageToProcess(10000); eventSignal.WaitOne(10000); } Assert.IsTrue(discoveredDevices.Any()); Assert.IsFalse(discoveredDevices.Any((d) => { return !d.Usn.StartsWith(publishedDevice.Devices.First().Udn); })); }
/// <summary> /// Start converting the specified file or folder. The file or files will added to the /// main library after conversion. For a file on an audio CD, this is equivalent to /// importing the song. Use CurrentEncoder to set the current encoder before converting. /// </summary> /// <param name="path"></param> /// <returns></returns> public Track ConvertFile2(string path) { return Invoke((Func<Track>)delegate { System.Threading.ManualResetEvent reset = new System.Threading.ManualResetEvent(false); iTunesConvertOperationStatus status = itunes.ConvertFile2(path); status.OnConvertOperationCompleteEvent += delegate { // this anonymous callback delegate signals the scanner // thread to continue... reset.Set(); }; // wait for the current conversion to complete, otherwise iTunes // raises an exception when concurrent conversions are requested reset.WaitOne(); reset.Reset(); reset = null; Track track = null; if (status.Tracks.Count > 0) { track = new Track(status.Tracks[1]); } Release(status); return track; }); }
public static void RealMain(string[] args) { //If we are on Windows, append the bundled "win-tools" programs to the search path //We add it last, to allow the user to override with other versions if (!Library.Utility.Utility.IsClientLinux) { Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + System.IO.Path.PathSeparator.ToString() + System.IO.Path.Combine( System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "win-tools") ); } //If this executable is invoked directly, write to console, otherwise throw exceptions bool writeConsole = System.Reflection.Assembly.GetEntryAssembly() == System.Reflection.Assembly.GetExecutingAssembly(); //If we are on windows we encrypt the database by default //We do not encrypt on Linux as most distros use a SQLite library without encryption support, //Linux users can use an encrypted home folder, or install a SQLite library with encryption support if (!Library.Utility.Utility.IsClientLinux && string.IsNullOrEmpty(Environment.GetEnvironmentVariable(DB_KEY_ENV_NAME))) { //Note that the password here is a default password and public knowledge // //The purpose of this is to prevent casual read of the database, as well // as protect from harddisk string scans, not to protect from determined // attacks. // //If you desire better security, start Duplicati once with the commandline option // --unencrypted-database to decrypt the database. //Then set the environment variable DUPLICATI_DB_KEY to the desired key, // and run Duplicati again without the --unencrypted-database option // to re-encrypt it with the new key // //If you change the key, please note that you need to supply the same // key when restoring the setup, as the setup being backed up will // be encrypted as well. Environment.SetEnvironmentVariable(DB_KEY_ENV_NAME, Library.AutoUpdater.AutoUpdateSettings.AppName + "_Key_42"); } //Find commandline options here for handling special startup cases Dictionary<string, string> commandlineOptions = Duplicati.Library.Utility.CommandLineParser.ExtractOptions(new List<string>(args)); foreach(string s in args) if ( s.Equals("help", StringComparison.InvariantCultureIgnoreCase) || s.Equals("/help", StringComparison.InvariantCultureIgnoreCase) || s.Equals("usage", StringComparison.InvariantCultureIgnoreCase) || s.Equals("/usage", StringComparison.InvariantCultureIgnoreCase)) commandlineOptions["help"] = ""; //If the commandline issues --help, just stop here if (commandlineOptions.ContainsKey("help")) { if (writeConsole) { Console.WriteLine(Strings.Program.HelpDisplayDialog); foreach(Library.Interface.ICommandLineArgument arg in SupportedCommands) Console.WriteLine(Strings.Program.HelpDisplayFormat(arg.Name, arg.LongDescription)); return; } else { throw new Exception("Server invoked with --help"); } } #if DEBUG //Log various information in the logfile if (!commandlineOptions.ContainsKey("log-file")) { commandlineOptions["log-file"] = System.IO.Path.Combine(StartupPath, "Duplicati.debug.log"); commandlineOptions["log-level"] = Duplicati.Library.Logging.LogMessageType.Profiling.ToString(); } #endif // Allow override of the environment variables from the commandline if (commandlineOptions.ContainsKey("server-datafolder")) Environment.SetEnvironmentVariable(DATAFOLDER_ENV_NAME, commandlineOptions["server-datafolder"]); if (commandlineOptions.ContainsKey("server-encryption-key")) Environment.SetEnvironmentVariable(DB_KEY_ENV_NAME, commandlineOptions["server-encryption-key"]); //Set the %DUPLICATI_HOME% env variable, if it is not already set if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(DATAFOLDER_ENV_NAME))) { #if DEBUG //debug mode uses a lock file located in the app folder Environment.SetEnvironmentVariable(DATAFOLDER_ENV_NAME, StartupPath); #else bool portableMode = commandlineOptions.ContainsKey("portable-mode") ? Library.Utility.Utility.ParseBool(commandlineOptions["portable-mode"], true) : false; if (portableMode) { //Portable mode uses a data folder in the application home dir Environment.SetEnvironmentVariable(DATAFOLDER_ENV_NAME, System.IO.Path.Combine(StartupPath, "data")); } else { //Normal release mode uses the systems "Application Data" folder Environment.SetEnvironmentVariable(DATAFOLDER_ENV_NAME, System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Library.AutoUpdater.AutoUpdateSettings.AppName)); } #endif } try { try { //This will also create Program.DATAFOLDER if it does not exist Instance = new SingleInstance(Duplicati.Library.AutoUpdater.AutoUpdateSettings.AppName, Program.DATAFOLDER); } catch (Exception ex) { if (writeConsole) { Console.WriteLine(Strings.Program.StartupFailure(ex)); return; } else { throw new Exception(Strings.Program.StartupFailure(ex)); } } if (!Instance.IsFirstInstance) { if (writeConsole) { Console.WriteLine(Strings.Program.AnotherInstanceDetected); return; } else { throw new SingleInstance.MultipleInstanceException(Strings.Program.AnotherInstanceDetected); } } // Setup the log redirect Duplicati.Library.Logging.Log.CurrentLog = Program.LogHandler; if (commandlineOptions.ContainsKey("log-file")) { if (System.IO.File.Exists(commandlineOptions["log-file"])) System.IO.File.Delete(commandlineOptions["log-file"]); var loglevel = Duplicati.Library.Logging.LogMessageType.Error; if (commandlineOptions.ContainsKey("log-level")) Enum.TryParse<Duplicati.Library.Logging.LogMessageType>(commandlineOptions["log-level"], true, out loglevel); Program.LogHandler.SetServerFile(commandlineOptions["log-file"], loglevel); } Version sqliteVersion = new Version((string)Duplicati.Library.SQLiteHelper.SQLiteLoader.SQLiteConnectionType.GetProperty("SQLiteVersion").GetValue(null, null)); if (sqliteVersion < new Version(3, 6, 3)) { if (writeConsole) { //The official Mono SQLite provider is also broken with less than 3.6.3 Console.WriteLine(Strings.Program.WrongSQLiteVersion(sqliteVersion, "3.6.3")); return; } else { throw new Exception(Strings.Program.WrongSQLiteVersion(sqliteVersion, "3.6.3")); } } //Create the connection instance System.Data.IDbConnection con = (System.Data.IDbConnection)Activator.CreateInstance(Duplicati.Library.SQLiteHelper.SQLiteLoader.SQLiteConnectionType); try { DatabasePath = System.IO.Path.Combine(Program.DATAFOLDER, "Duplicati-server.sqlite"); if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(DatabasePath))) System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(DatabasePath)); #if DEBUG //Default is to not use encryption for debugging Program.UseDatabaseEncryption = commandlineOptions.ContainsKey("unencrypted-database") ? !Library.Utility.Utility.ParseBool(commandlineOptions["unencrypted-database"], true) : false; #else Program.UseDatabaseEncryption = commandlineOptions.ContainsKey("unencrypted-database") ? !Library.Utility.Utility.ParseBool(commandlineOptions["unencrypted-database"], true) : true; #endif con.ConnectionString = "Data Source=" + DatabasePath; //Attempt to open the database, handling any encryption present OpenDatabase(con); Duplicati.Library.SQLiteHelper.DatabaseUpgrader.UpgradeDatabase(con, DatabasePath, typeof(Duplicati.Server.Database.Connection)); } catch (Exception ex) { //Unwrap the reflection exceptions if (ex is System.Reflection.TargetInvocationException && ex.InnerException != null) ex = ex.InnerException; if (writeConsole) { Console.WriteLine(Strings.Program.DatabaseOpenError(ex.Message)); return; } else { throw new Exception(Strings.Program.DatabaseOpenError(ex.Message), ex); } } DataConnection = new Duplicati.Server.Database.Connection(con); if (!DataConnection.ApplicationSettings.FixedInvalidBackupId) DataConnection.FixInvalidBackupId(); if (commandlineOptions.ContainsKey("webservice-password")) Program.DataConnection.ApplicationSettings.SetWebserverPassword(commandlineOptions["webservice-password"]); ApplicationExitEvent = new System.Threading.ManualResetEvent(false); Duplicati.Library.AutoUpdater.UpdaterManager.OnError += (Exception obj) => { Program.DataConnection.LogError(null, "Error in updater", obj); }; UpdatePoller = new UpdatePollThread(); DateTime lastPurge = new DateTime(0); System.Threading.TimerCallback purgeTempFilesCallback = (x) => { try { if (Math.Abs((DateTime.Now - lastPurge).TotalHours) < 23) return; lastPurge = DateTime.Now; foreach(var e in Program.DataConnection.GetTempFiles().Where((f) => f.Expires < DateTime.Now)) { try { if (System.IO.File.Exists(e.Path)) System.IO.File.Delete(e.Path); } catch (Exception ex) { Program.DataConnection.LogError(null, string.Format("Failed to delete temp file: {0}", e.Path), ex); } Program.DataConnection.DeleteTempFile(e.ID); } Duplicati.Library.Utility.TempFile.RemoveOldApplicationTempFiles((path, ex) => { Program.DataConnection.LogError(null, string.Format("Failed to delete temp file: {0}", path), ex); }); string pts; if (!commandlineOptions.TryGetValue("log-retention", out pts)) pts = DEFAULT_LOG_RETENTION; Program.DataConnection.PurgeLogData(Library.Utility.Timeparser.ParseTimeInterval(pts, DateTime.Now, true)); } catch (Exception ex) { Program.DataConnection.LogError(null, "Failed during temp file cleanup", ex); } }; try { PurgeTempFilesTimer = new System.Threading.Timer(purgeTempFilesCallback, null, TimeSpan.FromHours(1), TimeSpan.FromDays(1)); } catch (ArgumentOutOfRangeException) { //Bugfix for older Mono, slightly more resources used to avoid large values in the period field PurgeTempFilesTimer = new System.Threading.Timer(purgeTempFilesCallback, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1)); } LiveControl = new LiveControls(DataConnection.ApplicationSettings); LiveControl.StateChanged += new EventHandler(LiveControl_StateChanged); LiveControl.ThreadPriorityChanged += new EventHandler(LiveControl_ThreadPriorityChanged); LiveControl.ThrottleSpeedChanged += new EventHandler(LiveControl_ThrottleSpeedChanged); Program.WorkThread = new Duplicati.Library.Utility.WorkerThread<Runner.IRunnerData>((x) => { Runner.Run(x, true); }, LiveControl.State == LiveControls.LiveControlState.Paused); Program.Scheduler = new Scheduler(WorkThread); Program.WorkThread.StartingWork += (worker, task) => { SignalNewEvent(null, null); }; Program.WorkThread.CompletedWork += (worker, task) => { SignalNewEvent(null, null); }; Program.WorkThread.WorkQueueChanged += (worker) => { SignalNewEvent(null, null); }; Program.Scheduler.NewSchedule += new EventHandler(SignalNewEvent); Program.WorkThread.OnError += (worker, task, exception) => { Program.DataConnection.LogError(task == null ? null : task.BackupID, "Error in worker", exception); }; Action<long, Exception> registerTaskResult = (id, ex) => { lock(Program.MainLock) { // If the new results says it crashed, we store that instead of success if (Program.TaskResultCache.Count > 0 && Program.TaskResultCache.Last().Key == id) { if (ex != null && Program.TaskResultCache.Last().Value == null) Program.TaskResultCache.RemoveAt(Program.TaskResultCache.Count - 1); else return; } Program.TaskResultCache.Add(new KeyValuePair<long, Exception>(id, ex)); while(Program.TaskResultCache.Count > MAX_TASK_RESULT_CACHE_SIZE) Program.TaskResultCache.RemoveAt(0); } }; Program.WorkThread.CompletedWork += (worker, task) => { registerTaskResult(task.TaskID, null); }; Program.WorkThread.OnError += (worker, task, exception) => { registerTaskResult(task.TaskID, exception); }; Program.WebServer = new WebServer.Server(commandlineOptions); if (Program.WebServer.Port != DataConnection.ApplicationSettings.LastWebserverPort) ServerPortChanged = true; DataConnection.ApplicationSettings.LastWebserverPort = Program.WebServer.Port; if (Library.Utility.Utility.ParseBoolOption(commandlineOptions, "ping-pong-keepalive")) { Program.PingPongThread = new System.Threading.Thread(PingPongMethod); Program.PingPongThread.IsBackground = true; Program.PingPongThread.Start(); } ServerStartedEvent.Set(); ApplicationExitEvent.WaitOne(); } catch (SingleInstance.MultipleInstanceException mex) { System.Diagnostics.Trace.WriteLine(Strings.Program.SeriousError(mex.ToString())); if (writeConsole) Console.WriteLine(Strings.Program.SeriousError(mex.ToString())); else throw mex; } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(Strings.Program.SeriousError(ex.ToString())); if (writeConsole) Console.WriteLine(Strings.Program.SeriousError(ex.ToString())); else throw new Exception(Strings.Program.SeriousError(ex.ToString()), ex); } finally { StatusEventNotifyer.SignalNewEvent(); if (UpdatePoller != null) UpdatePoller.Terminate(); if (Scheduler != null) Scheduler.Terminate(true); if (WorkThread != null) WorkThread.Terminate(true); if (Instance != null) Instance.Dispose(); if (PurgeTempFilesTimer != null) PurgeTempFilesTimer.Dispose(); if (PingPongThread != null) try { PingPongThread.Abort(); } catch { } if (LogHandler != null) LogHandler.Dispose(); } }
public static int RunCommand (string path, string args, string[] env = null, StringBuilder output = null, bool suppressPrintOnErrors = false) { Exception stdin_exc = null; var info = new ProcessStartInfo (path, args); info.UseShellExecute = false; info.RedirectStandardInput = false; info.RedirectStandardOutput = true; info.RedirectStandardError = true; System.Threading.ManualResetEvent stdout_completed = new System.Threading.ManualResetEvent (false); System.Threading.ManualResetEvent stderr_completed = new System.Threading.ManualResetEvent (false); if (output == null) output = new StringBuilder (); if (env != null){ if (env.Length % 2 != 0) throw new Exception ("You passed an environment key without a value"); for (int i = 0; i < env.Length; i+= 2) info.EnvironmentVariables [env[i]] = env[i+1]; } if (verbose > 0) Console.WriteLine ("{0} {1}", path, args); using (var p = Process.Start (info)) { p.OutputDataReceived += (s, e) => { if (e.Data != null) { lock (output) output.AppendLine (e.Data); } else { stdout_completed.Set (); } }; p.ErrorDataReceived += (s, e) => { if (e.Data != null) { lock (output) output.AppendLine (e.Data); } else { stderr_completed.Set (); } }; p.BeginOutputReadLine (); p.BeginErrorReadLine (); p.WaitForExit (); stderr_completed.WaitOne (TimeSpan.FromSeconds (1)); stdout_completed.WaitOne (TimeSpan.FromSeconds (1)); if (p.ExitCode != 0) { // note: this repeat the failing command line. However we can't avoid this since we're often // running commands in parallel (so the last one printed might not be the one failing) if (!suppressPrintOnErrors) Console.Error.WriteLine ("Process exited with code {0}, command:\n{1} {2}{3}", p.ExitCode, path, args, output.Length > 0 ? "\n" + output.ToString () : string.Empty); return p.ExitCode; } else if (verbose > 0 && output.Length > 0 && !suppressPrintOnErrors) { Console.WriteLine (output.ToString ()); } if (stdin_exc != null) throw stdin_exc; } return 0; }
public void Run( EasyHook.RemoteHooking.IContext context, String channelName, CaptureConfig config) { // When not using GAC there can be issues with remoting assemblies resolving correctly // this is a workaround that ensures that the current assembly is correctly associated AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += (sender, args) => { return this.GetType().Assembly.FullName == args.Name ? this.GetType().Assembly : null; }; // NOTE: This is running in the target process _interface.Message(MessageType.Information, "Injected into process Id:{0}.", EasyHook.RemoteHooking.GetCurrentProcessId()); _runWait = new System.Threading.ManualResetEvent(false); _runWait.Reset(); try { // Initialise the Hook if (!InitialiseDirectXHook(config)) { return; } _interface.Disconnected += _clientEventProxy.DisconnectedProxyHandler; // Important Note: // accessing the _interface from within a _clientEventProxy event handler must always // be done on a different thread otherwise it will cause a deadlock _clientEventProxy.Disconnected += () => { // We can now signal the exit of the Run method _runWait.Set(); }; // We start a thread here to periodically check if the host is still running // If the host process stops then we will automatically uninstall the hooks StartCheckHostIsAliveThread(); // Wait until signaled for exit either when a Disconnect message from the host // or if the the check is alive has failed to Ping the host. _runWait.WaitOne(); // we need to tell the check host thread to exit (if it hasn't already) StopCheckHostIsAliveThread(); // Dispose of the DXHook so any installed hooks are removed correctly DisposeDirectXHook(); } catch (Exception e) { _interface.Message(MessageType.Error, "An unexpected error occured: {0}", e.ToString()); } finally { try { _interface.Message(MessageType.Information, "Disconnecting from process {0}", EasyHook.RemoteHooking.GetCurrentProcessId()); } catch { } // Remove the client server channel (that allows client event handlers) System.Runtime.Remoting.Channels.ChannelServices.UnregisterChannel(_clientServerChannel); // Always sleep long enough for any remaining messages to complete sending System.Threading.Thread.Sleep(100); } }
public void whenEnoughMoneyHasBeenInsertedToBuyItemThenThankTheUserAndNextReadResetsDisplay() { // Special arrangements here as we need to ensure events are complete // before enforcing our assertions System.Threading.ManualResetEvent eventProduct = new System.Threading.ManualResetEvent(false); System.Threading.ManualResetEvent eventNextRead = new System.Threading.ManualResetEvent(false); bool wasProductRaised = false; bool wasReadRaised = false; // Insert coins this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfQuarter, InsertableCoinSizes.SizeOfQuarter); this._vendingMachine.InsertCoin(InsertableCoinWeights.WeightOfQuarter, InsertableCoinSizes.SizeOfQuarter); // Tricky, after product is dispensed, we will set thank you message, but ALSO on next read // it will be a different message. Wait for product changed handler to complete. this._vendingMachine.ProductSelectorButtons.OnSelectedProductChanged += delegate (object sender, ProductForSale e) { wasProductRaised = true; eventProduct.Set(); }; this._vendingMachine.Display.OnNextRead += delegate (object sender, EventArgs e) { wasReadRaised = true; eventNextRead.Set(); }; // This will start the events firing this._vendingMachine.ProductSelectorButtons.SelectedProduct = ProductForSale.Chips; eventProduct.WaitOne(5000, false); Assert.IsTrue(wasProductRaised); // Ensures no false positive from a timeout Assert.AreEqual((decimal)0.50, this._vendingMachine.CurrentAmountInserted); // Make sure current amount inserted remains untouched until next read string dummy = this._vendingMachine.Display.Message; eventNextRead.WaitOne(5000, false); Assert.IsTrue(wasReadRaised); // Ensures no false positive from a timeout Assert.AreEqual((decimal)0.00, this._vendingMachine.CurrentAmountInserted); // Make sure current amount inserted is reset after read Assert.AreEqual(VendingMachine.VendingMachine.ThankYouMessage, this._vendingMachine.Display.PreviousMessage); Assert.AreEqual(VendingMachine.VendingMachine.InsertCoinsMessage, this._vendingMachine.Display.Message); }
// WARNING: This will be called from a thread! protected override void LoadFromDevice () { import_reset_event = new System.Threading.ManualResetEvent (false); importer = new DatabaseImportManager (this) { KeepUserJobHidden = true, SkipHiddenChildren = false }; importer.Finished += OnImportFinished; foreach (string audio_folder in BaseDirectories) { importer.Enqueue (audio_folder); } import_reset_event.WaitOne (); }