public void Close() { if (this.Closing == true) { return; } lock (this.ConnectionLock) { this.Logger.OnMessageLog("Closing"); try { this.Closing = true; ObjectUtils.DisposeQuietly(this.Stream); this.Stream = null; ObjectUtils.DisposeQuietly(this.Client); this.Client = null; ThreadUtils.InterruptAndJoin(this.ConnectionThread); this.ConnectionThread = null; } finally { this.Closing = false; } this.Logger.OnMessageLog("Closed"); } }
private String protectedPathInForeground(String adjustedPath, byte[] data) { try { return(pathInForeground(adjustedPath, data)); } catch (Exception e) { ThreadUtils.checkInterrupted(e); if ((e is KeeperException.ConnectionLossException || !(e is KeeperException)) && protectedId != null) { /* * CURATOR-45 + CURATOR-79: we don't know if the create operation was successful or not, * register the znode to be sure it is deleted later. */ new FindAndDeleteProtectedNodeInBackground(client, ZKPaths.getPathAndNode(adjustedPath).getPath(), protectedId).execute(); /* * The current UUID is scheduled to be deleted, it is not safe to use it again. * If this builder is used again later create a new UUID */ protectedId = Guid.NewGuid().ToString(); } throw e; } }
public void Start() { ThreadUtils.Delay(firstPushWindow * 1000).ContinueWith((t) => { SendBulkEvents(); PeriodicTaskFactory.Start(() => { SendBulkEvents(); }, interval * 1000, cancellationTokenSource.Token); }); }
/// <summary> /// 保存程序(新建程序需要调用SaveTo, 指定要保存的路径) /// </summary> /// <param name="onSaving"></param> /// <param name="onFinished"></param> /// <param name="onError"></param> /// <param name="onFinally"></param> public void Save(string filePath, Action onSaving, OnFinished onFinished, OnError onError, Action onFinally) { ThreadUtils.Run(() => { Stream fstream = null; try { onSaving?.Invoke(); fstream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write); BinaryFormatter binFormat = new BinaryFormatter(); binFormat.Serialize(fstream, this); onFinished?.Invoke(); } catch (Exception e) { //throw e; onError?.Invoke(-1, e.ToString()); } finally { if (fstream != null) { fstream.Close(); } onFinally?.Invoke(); } }); }
private void OnFinishReceivingFiles() { StopTimer(); lock (this) { if (!Canceled) { ThreadUtils.RunOnUiAndWait(() => { Status = "Done!"; Percent = 100; if (_receivedFiles != null && _receivedFiles.Count == _session.WillReceiveFiles.Count) { OnReceivedSuccessfully(_receivedFiles); } }); Thread.Sleep(300); } } _currentReceiver = null; CloseUi(); }
private void WorkerThread() { Logger.DebugFormat("{0}", ThreadUtils.DumpThreadInfo()); while (!m_cancellationToken.Token.WaitHandle.WaitOne(m_recheckPeriod)) { try { var processesList = Process.GetProcesses(); var matchingProcesses = processesList.Where(x => m_processRegex.IsMatch(x.ProcessName)).ToArray(); var processToInject = matchingProcesses.Where(x => !m_processedProcesses.Contains(x.Id)).ToArray(); if (processToInject.Any()) { Logger.DebugFormat("Found {0} target process(es):\r\n\t{1}", processToInject.Length, String.Join("\r\n\t", processToInject.Select(x => String.Format("[{0}] {1}, mainModule {2}", x.Id, x.ProcessName, x.MainModule)))); foreach (var process in processToInject) { ProcessFound(this, new EventArgs <Process>(process)); m_processedProcesses.Add(process.Id); } } } catch (Exception ex) { Logger.Error("Exception occured in task cycle", ex); } } }
public void Shutdown() { if (_client == null) { logger.InfoFormat("_client already closed."); return; } working = false; // watching = false; ThreadUtils.TryStopThreadByWait(bytesReceiveThread, 200, 300, "BytesReceiveThread"); try { _client.Shutdown(SocketShutdown.Both); logger.InfoFormat("_client.Shutdown done"); } catch (Exception e) { logger.Error("_client.Shutdown error", e); } try { _client.Close(); logger.InfoFormat("_client.Close done"); } catch (Exception e) { logger.Error("_client.Close error", e); } _client = null; }
private void Keyboard_KeyPressed(object sender, KeyEventArgs e) { if (!WaitDescriptor.IsMatch(e)) { return; } var time = DateTime.Now; if (time.TimeOfDay - _lastPressTime.TimeOfDay > _maxKeysPressingInterval) { _currentPressCount = 0; } _lastPressTime = time; lock (s_counterSync) { _currentPressCount++; } PressedKeyArgs = e; if (_currentPressCount == PressTimes) { ThreadUtils.StartBackgroundThread(WaitForSet); } }
public void Stop() { lock (this.StateLock) { if (this.Started == true) { this.Logger.OnMessageLog("Stopping"); var listener = this.Listener; if (listener != null) { listener.Stop(); } ThreadUtils.InterruptAndJoin(this.AccepterThread); this.AccepterThread = null; lock (this.Connections) { foreach (var c in this.Connections) { c.Close(); } } this.Logger.OnMessageLog("Stopped"); this.Started = false; } } }
public void close() { log.Debug("Closing"); if (state.CompareAndSet(CuratorFrameworkState.STARTED, CuratorFrameworkState.STOPPED)) { listeners.forEach(listener => { ICuratorEvent @event = new CuratorEventImpl(this, CuratorEventType.CLOSING, 0, null, null, null, null, null, null, null, null); try { listener.eventReceived(this, @event); } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.Error("Exception while sending Closing event", e); } return(null); }); if (executorService != null) { executorService.Dispose(); } listeners.clear(); unhandledErrorListeners.clear(); connectionStateManager.Dispose(); client.Dispose(); namespaceWatcherMap.Dispose(); } }
internal String fixForNamespace(String path, bool isSequential) { if (ensurePathNeeded.get()) { try { CuratorZookeeperClient zookeeperClient = client.getZookeeperClient(); RetryLoop.callWithRetry ( zookeeperClient, CallableUtils.FromFunc <object>(() => { ZKPaths.mkdirs(zookeeperClient.getZooKeeper(), ZKPaths.makePath("/", @namespace), true, client.getAclProvider(), true); return(null); }) ); ensurePathNeeded.set(false); } catch (Exception e) { ThreadUtils.checkInterrupted(e); client.logError("Ensure path threw exception", e); } } return(ZKPaths.fixForNamespace(@namespace, path, isSequential)); }
public void start() { log.Info("Starting"); if (!state.CompareAndSet(CuratorFrameworkState.LATENT, CuratorFrameworkState.STARTED)) { throw new InvalidOperationException("Cannot be started more than once"); } try { connectionStateManager.start(); // ordering dependency - must be called before client.start() IConnectionStateListener listener = new ConnectedStateListener(); this.getConnectionStateListenable().addListener(listener); client.start(); executorService = ThreadUtils.newSingleThreadScheduledExecutor(GetType().FullName); executorService.submit(new FutureTask <object>(RunnableUtils.FromFunc(() => backgroundOperationsLoop()))); } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleBackgroundOperationException(null, e); } }
private void AsyncReportPrice(PriceAction act, int screenPrice, int targetPrice, DateTime screenTime, DateTime occurTime, string memo, int usedDelayMills = 0) { ThreadUtils.StartNewTaskSafe(() => { string actionText = null; if (act == PriceAction.PRICE_OFFER) { priceActionService.ReportPriceOffered(screenPrice, targetPrice, screenTime, occurTime, memo); actionText = screenTime.ToLongTimeString() + " - 出价: " + targetPrice; } else if (act == PriceAction.PRICE_SUBMIT) { priceActionService.ReportPriceSubbmitted(screenPrice, targetPrice, screenTime, usedDelayMills, occurTime, memo); actionText = screenTime + " - 提交"; } else if (act == PriceAction.PRICE_SHOW) { priceActionService.ReportPriceShowed(screenPrice, screenTime, occurTime, memo); } if (actionText != null) { SetStrategyText(); lastActions.Add(actionText); SetLastAcionText(); } }); }
/// <summary> /// 需要一个线程 收集页面信息 - 价格时间, 从11:29:00开始 /// </summary> private void StartCollectingThread() { StopCollectingThread(); isCollectingWork = true; collectingThread = ThreadUtils.StartNewBackgroudThread(LoopDetectPriceAndTimeInScreen); }
private void Listen() { EndPoint endPoint = new IPEndPoint(IPAddress.Any, _portNum); _socket.Bind(endPoint); var buffer = new byte[BufferSize]; while (_socket != null && _socket.IsBound && _active) { try { var received = _socket.ReceiveFrom(buffer, BufferSize, SocketFlags.None, ref endPoint); OnReceiveData.Dispatch(buffer, received, ((IPEndPoint)endPoint).Address); } catch (SocketException e) { if (_active) { UnityEngine.Debug.LogErrorFormat(e.ToString()); Stop(); } break; } catch (Exception e) { UnityEngine.Debug.LogError(e.ToString()); break; } } ThreadUtils.SafeAbortAndRemove(ref _thread); }
protected virtual void Dispose(bool disposing) { this.Listener?.Stop(); ThreadUtils.InterruptAndJoin(this.NetworkThread); ThreadUtils.InterruptAndJoin(this.AcceptThread); }
public void pegarAsync(float latitude, float longitude, GeoEnderecoEventHandler callback) { var location = new CLLocation(latitude, longitude); var geoCoder = new CLGeocoder(); geoCoder.ReverseGeocodeLocation(location, (placemarkers, error) => { if (placemarkers.Length > 0) { var geoEndereco = placemarkers[0]; var endereco = new GeoEnderecoInfo { Logradouro = geoEndereco.Thoroughfare, Complemento = geoEndereco.SubThoroughfare, Bairro = geoEndereco.SubLocality, Cidade = geoEndereco.Locality, Uf = geoEndereco.AdministrativeArea, CEP = geoEndereco.PostalCode, }; if (callback != null) { ThreadUtils.RunOnUiThread(() => { callback(null, new GeoEnderecoEventArgs(endereco)); }); } } }); }
public void Stop() { ThreadUtils.CheckIsOnMainThread(); if (_amState != AudioManagerState.Running) { return; } _amState = AudioManagerState.Uninitialized; UnregisterReceiver(_wiredHeadsetReceiver); //_bluetoothManager.Stop(); //restored previously stored audio states SetSpeakerphoneOn(_savedIsSpeackerPhoneOn); SetMicrophoneMute(_savedIsMicrophoneMute); _audioManager.Mode = _savedAudioMode; _audioManager.AbandonAudioFocus(_audioFocusChangeListener); _audioFocusChangeListener = null; if (_proximitySensor != null) { _proximitySensor.Stop(); _proximitySensor = null; } _audioManagerEvents = null; }
/// <summary> /// Initializes a new instance of the <see cref="StfLogger"/> class. /// </summary> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool Init() { LogInfoDetails = new Dictionary <string, string>(); AddLoglevelToRunReport = new Dictionary <StfLogLevel, bool>(); NumberOfLoglevelMessages = new Dictionary <StfLogLevel, int>(); ThreadUtils = new ThreadUtils(); foreach (StfLogLevel loglevel in Enum.GetValues(typeof(StfLogLevel))) { NumberOfLoglevelMessages.Add(loglevel, 0); AddLoglevelToRunReport.Add(loglevel, true); } LogFileHandle = new LogfileWriter { OverwriteLogFile = OverwriteLogFile }; SetDefaultConfiguration(); FileName = Configuration.LogFileName; LogLevel = Configuration.LogLevel; OverwriteLogFile = Configuration.OverwriteLogFile; // setting the default AID logging function LogAutomationIdObjectUserFunction = (level, obj, message) => LogOneHtmlMessage( level, $"AutomationId: [{obj.ToString()}] - Message: [{message}]"); LogFileInitialized = false; return(true); }
public void Start(IAudioManagerEvents audioManagerEvents) { ThreadUtils.CheckIsOnMainThread(); if (_amState == AudioManagerState.Running) { return; } _audioManagerEvents = audioManagerEvents; _amState = AudioManagerState.Running; // Store current audio state so we can restore it when stop() is called _savedAudioMode = _audioManager.Mode; _savedIsSpeackerPhoneOn = _audioManager.SpeakerphoneOn; _savedIsMicrophoneMute = _audioManager.MicrophoneMute; _hasWiredHeadset = HasWiredHeadset(); _audioFocusChangeListener = new OnAudioFocusChangeListener(); //var result = _audioManager.RequestAudioFocus(_audioFocusChangeListener,Stream.VoiceCall,AudioFocus.GainTransient); _audioManager.Mode = Mode.InCommunication; _proximitySensor.Start(); SetMicrophoneMute(false); _userSelectedAudioDevice = AudioDevice.None; _selectedAudioDevice = AudioDevice.None; _audioDevices.Clear(); UpdateAudioDeviceState(); RegisterReceiver(_wiredHeadsetReceiver, new IntentFilter(Intent.ActionHeadsetPlug)); }
public void TheBloodyHardAsyncInvokationPatter() { // You need to fill in the 3 ___'s with A,B & C in the order they will execute var called = ""; var sub = new Subject <double>(); Func <int, double> halve = x => { called += _____; return(x * 0.5); }; double?result = 0; sub.Subscribe(n => { called += ____; result = n; }); halve.BeginInvoke(101, iar => { called += ______; sub.OnNext(halve.EndInvoke(iar)); sub.OnCompleted(); }, null); ThreadUtils.WaitUntil(() => result != 0); Assert.AreEqual(50.5, result); Assert.AreEqual("ABC", called); }
private WorkThreadDictionary(Thread thread) { Contract.Requires <ArgumentNullException>(thread != null); g_pValues = new List <object>(); g_pKeys = new List <string>(); ThreadUtils.SetObject(thread, this); }
/// <summary> /// 出价 - /// 1. 输入价格 - 移动到输入框位置,点击,清空历史数据,输入新价格 /// 2. 点击出价按钮 - 移动到按钮位置,点击 /// 3. 对验证码区域截图 且 上传 /// </summary> public void OfferPrice(int targetPrice, bool enableCancelFirst, Func <CaptchaAnswerImage, bool> callbackFunc = null) { // 0. 出价前,先尝试取消,防止上一步的可能的遮罩 if (enableCancelFirst) { // this.CancelOfferedPrice(); actionManager.ClickButtonByFenceWayRToL(actionManager.AddDelta(742, 502)); } // 1. 输入价格 且 出价 // TODO: 坐标方法 - 应该抽取出来单独管理 actionManager.InputTextAtPoint(actionManager.AddDelta(676, 417), targetPrice.ToString(), true, "第二阶段出价"); actionManager.ClickButtonAtPoint(actionManager.AddDelta(800, 415), true, "第二阶段出价"); // 2. 对验证码区域截屏且上传 // 这里尝试异步 ThreadUtils.StartNewTaskSafe(() => { // 这里等待会阻塞进程 KK.Sleep(390); CaptchaAnswerImage img = CaptureCaptchaImage(); UploadCaptchaImage(img); callbackFunc?.Invoke(img); } ); // return img; }
public DownloaderAndroid() { _cliente = new WebClient(); _cliente.DownloadProgressChanged += (sender, e) => { //Context context = Android.App.Application.Context; if (_aoProcessar != null) { ThreadUtils.RunOnUiThread(() => { _aoProcessar(sender, new AoProcessarArgs(e.ProgressPercentage, e.BytesReceived, e.TotalBytesToReceive)); }); } }; _cliente.DownloadFileCompleted += (sender, e) => { if (e.Cancelled) { if (_aoCancelar != null) { _aoCancelar(sender, e); } } else { if (_aoCompletar != null) { _aoCompletar(sender, e); } } }; }
/** * Convenience utility: creates a "session fail" retry loop calling the given proc * * @param client Zookeeper * @param mode how to handle session failures * @param proc procedure to call with retry * @param <T> return type * @return procedure result * @throws Exception any non-retriable errors */ public static T callWithRetry <T>(CuratorZookeeperClient client, Mode mode, ICallable <T> proc) { T result = default(T); SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(mode); retryLoop.start(); try { while (retryLoop.shouldContinue()) { try { result = proc.call(); } catch (Exception e) { ThreadUtils.checkInterrupted(e); retryLoop.takeException(e); } } } finally { retryLoop.Dispose(); } return(result); }
public override void OnShutdown() { _isThreadsActive = false; Manager.Shutdown(); ThreadUtils.JoinIgnoreErrors(_hardwareUpdaterThread); }
private void buttonNewKey_Click(object sender, EventArgs e) { Process process; try { process = _openPgp.GenerateKey(); } #region Error handling catch (IOException ex) { Log.Error(ex); Msg.Inform(this, ex.Message, MsgSeverity.Error); return; } #endregion ThreadUtils.StartBackground(() => { process.WaitForExit(); // Update key list when done try { Invoke(new Action(ListKeys)); } #region Sanity checks catch (InvalidOperationException) { // Ignore if window has been dispoed } #endregion }, name: "WaitForOpenPgp"); }
public override void Play(AudioDevice dev) { ThreadUtils.StartBackgroundThread(WaitStopEvent); var count = _dataLen; _stream.Position = 100; while (!IsStopped && count > 0) { var read = _stream.Read(s_sampleBuffer, 0, Math.Min(BUFFER_SIZE, count)); if (read <= 0) { break; } count -= read; dev.PlaySample(s_sampleBuffer, read / _frameDivider); } if (IsStopped) { dev.StopPlaying(); } else { dev.WaitForPlayingFinished(); } dev.Close(); PlayingFinishedEvent.Set(); }
/// <summary> /// Executes a "0install-win" command in-process in a new thread. Returns immediately. /// </summary> /// <param name="callback">A callback method to be raised once the command has finished executing. Uses <see cref="SynchronizationContext"/> of calling thread. Can be <c>null</c>.</param> /// <param name="machineWide">Appends --machine to <paramref name="args"/> if <c>true</c>.</param> /// <param name="args">Command name with arguments to execute.</param> internal static void RunCommand(Action?callback, bool machineWide, params string[] args) { if (machineWide) { args = args.Append("--machine"); } var context = SynchronizationContext.Current; ThreadUtils.StartAsync( () => { Log.Debug($"Launching {Commands.WinForms.Program.ExeName} in-process with arguments: {args.JoinEscapeArguments()}"); using (var handler = new GuiCommandHandler()) ProgramUtils.Run(Commands.WinForms.Program.ExeName, args, handler); if (callback != null) { try { context.Send(state => callback(), null); } catch (InvalidAsynchronousStateException) { // Ignore callback if UI was closed in the meantime } } }, "0install-win (" + args.JoinEscapeArguments() + ")"); }
private bool DragAreaWithVerticalCheck(Point start, Point end) { using (var capture1 = new ScreenCapture(VerticalCheckRect.Value)) { MouseUtils.RightDrag(start, end, ScrollDelay); using (var capture2 = new ScreenCapture(VerticalCheckRect.Value)) { if (!BitmapComparer.AreBitmapsIdentical(capture1.Bitmap, capture2.Bitmap)) { sm_log.Info("Drag successful"); return(true); } sm_log.Warn(Invariant($"Attempted to drag from {start} to {end} but detected no vertical movement. Waiting a little while before checking again...")); ThreadUtils.SleepOrAbort(100 + ScrollDelay); using (var capture3 = new ScreenCapture(VerticalCheckRect.Value)) { if (!BitmapComparer.AreBitmapsIdentical(capture1.Bitmap, capture3.Bitmap)) { sm_log.Info("Drag successful"); return(true); } sm_log.Warn("Still no vertical movement detected"); return(false); } } } }