private void Compress(object i) { try { while (!Cancelled) { ByteBlock _block = QueueReader.Dequeue(); if (_block == null) { return; } using (MemoryStream _memoryStream = new MemoryStream()) { using (GZipStream cs = new GZipStream(_memoryStream, CompressionMode.Compress)) { cs.Write(_block.Buffer, 0, _block.Buffer.Length); } byte[] compressedData = _memoryStream.ToArray(); ByteBlock _out = new ByteBlock(_block.ID, compressedData); QueueWriter.EnqueueForWriting(_out); } WaitHandle doneEvent = DoneEvents[(int)i]; doneEvent.Dispose(); } } catch (Exception ex) { Console.WriteLine("Ошибка в номере потока {0}. \n описание ошибки: {1}", i, ex.Message); Cancelled = true; } }
/// <devdoc> /// Make sure we are not watching for process exit. /// </devdoc> /// <internalonly/> private void StopWatchingForExit() { if (_watchingForExit) { RegisteredWaitHandle rwh = null; WaitHandle wh = null; lock (this) { if (_watchingForExit) { _watchingForExit = false; wh = _waitHandle; _waitHandle = null; rwh = _registeredWaitHandle; _registeredWaitHandle = null; } } if (rwh != null) { rwh.Unregister(null); } if (wh != null) { wh.Dispose(); } } }
public void Dispose() { #if !COREFX WaitHandle.Close(); #endif WaitHandle.Dispose(); IsClose = true; }
public static void PlatformSpecificDispose(WaitHandle wh) { #if DOTNETSTANDARD_1_3 wh?.Dispose(); #else wh?.Close(); #endif }
/// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } WaitHandle?.Dispose(); base.Dispose(disposing); }
private static void EndWrapperInvoke(IAsyncResult ar) { _wrapperInstance.EndInvoke(ar); WaitHandle asyncWaitHandle = ar.AsyncWaitHandle; if (asyncWaitHandle != null) { asyncWaitHandle.Close(); asyncWaitHandle.Dispose(); } }
protected void Dispose(bool disposing) { if (disposing) { if (WaitHandle != null) { WaitHandle.Dispose(); WaitHandle = null; } } }
protected virtual void Dispose(bool disposing) { if (!m_disposed) { if (disposing) { WaitHandle.Dispose(); } m_disposed = true; } }
public void Dispose() { if (!_disposed) { if (_waitHandle != null) { _waitHandle.Dispose(); } _disposed = true; } }
private bool disposedValue = false; // To detect redundant calls /// <inheritdoc /> protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { settingsMem?.Dispose(); waitHandle?.Dispose(); } disposedValue = true; } }
public static void CloseOrDispose(this WaitHandle handle) { if (handle == null) { return; } #if NETSTANDARD handle.Dispose(); #else handle.Close(); #endif }
/// <summary> /// Releases resources associated to this object. /// </summary> public void Dispose() { if (!_isDisposed) { _processHandle.Dispose(); _waitHandle.Dispose(); _standardInput?.Dispose(); _standardOutput?.Dispose(); _standardError?.Dispose(); _isDisposed = true; } }
protected virtual void Dispose(bool disposing) { if (IsDisposed) { return; } if (disposing) { WaitHandle.Dispose(); } IsDisposed = true; }
public void SetPort(int port) { MyPort = port; Invoke(new Action( () => { Text = $"Port: {port}"; SetLabel($"Port: {port}"); listeningForDataToolStripMenuItem.Checked = true; })); WaitHandle?.Dispose(); WaitHandle = CommunicationHelper.LetDudeKnowWereListeningOnSomePort(Process.GetCurrentProcess().Id); }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { _timer.Dispose(); _autoEvent.Dispose(); _waitHandle.Dispose(); } _disposed = true; }
private void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { WaitHandle?.Dispose(); } } finally { m_disposed = true; // Prevent duplicate dispose. } } }
private static async Task DispatchReceiveStop(IBusControl busControl, WaitHandle waitHandle, Func <Message, Task> dispatcher, int timeout = DefaultWaitTimeout) { await busControl.StartAsync(); var message = new Message { Payload = ExpectedMessage }; await dispatcher(message); if (!waitHandle.WaitOne(timeout)) { throw new TimeoutException($"Timeout of {timeout}ms expired"); } waitHandle.Dispose(); await busControl.StopAsync(); }
protected virtual void Dispose(bool disposing) { if (IsDisposed) { return; } if (disposing) { WaitHandle.Set(); //Free managed resources WaitHandle.Dispose(); } //Free unmanaged resources IsDisposed = true; }
public void Dispose() { _processHandle.Dispose(); _exitedWaitHandle.Dispose(); if (!_isPseudoConsoleDisposed) { // This will terminate the process tree (unless we are on Windows 1809). _pseudoConsole?.Dispose(); if (WindowsVersion.NeedsWorkaroundForWindows1809) { // Should always succeed. Kill(); } _isPseudoConsoleDisposed = true; } }
/// <summary> /// Releases all resources used by the CancelEvent. /// </summary> /// <param name="disposing">Specifies whether or not this was called from Dispose().</param> protected virtual void Dispose(bool disposing) { if (m_bOwnOriginal && m_hOriginalCancel != null) { m_hOriginalCancel.Dispose(); m_hOriginalCancel = null; } foreach (Tuple <WaitHandle, bool, string> item in m_rgCancel) { if (item.Item2) { item.Item1.Dispose(); } } m_rgCancel.Clear(); m_rgHandles = null; }
public void Dispose() { if (_connectedEvent != null) { _connectedEvent.Dispose(); } if (addressesSet != null) { addressesSet.Dispose(); } if (cancellationTokenSource != null) { cancellationTokenSource.Dispose(); } if (tcpClient.Connected) { this.tcpClient.Close(); } }
public void Dispose() { if (_waitHandle == null) { return; } if (_hasHandle && _waitHandle is Mutex) { ((Mutex)_waitHandle).ReleaseMutex(); #if NETSTANDARD _waitHandle.Dispose(); #else _waitHandle.Close(); #endif } if (_hasHandle && _waitHandle is AutoResetEvent) { ((AutoResetEvent)_waitHandle).Set(); } _waitHandle = null; }
private void StartConnect() { zooKeeper.State = ZooKeeper.States.CONNECTING; TcpClient tempClient = null; WaitHandle wh = null; do { if (zkEndpoints.EndPointID != -1) { try { Thread.Sleep(new TimeSpan(0, 0, 0, 0, random.Next(0, 50))); } #if !NET_CORE catch (ThreadInterruptedException e) { LOG.Error("Event thread exiting due to interruption", e); } #endif #if NET_CORE catch (Exception e) { } #endif if (!zkEndpoints.IsNextEndPointAvailable) { try { // Try not to spin too fast! Thread.Sleep(1000); } #if !NET_CORE catch (ThreadInterruptedException e) { LOG.Error("Event thread exiting due to interruption", e); } #endif #if NET_CORE catch (Exception e) { } #endif } } //advance through available connections; zkEndpoints.GetNextAvailableEndpoint(); Cleanup(tempClient); Console.WriteLine("Opening socket connection to server {0}", zkEndpoints.CurrentEndPoint.ServerAddress); #if !NET_CORE LOG.InfoFormat("Opening socket connection to server {0}", zkEndpoints.CurrentEndPoint.ServerAddress); #endif tempClient = new TcpClient(); tempClient.LingerState = new LingerOption(false, 0); tempClient.NoDelay = true; Interlocked.Exchange(ref initialized, 0); IsConnectionClosedByServer = false; try { IAsyncResult ar = tempClient.BeginConnect(zkEndpoints.CurrentEndPoint.ServerAddress.Address, zkEndpoints.CurrentEndPoint.ServerAddress.Port, null, null); wh = ar.AsyncWaitHandle; #if !NET_CORE if (!ar.AsyncWaitHandle.WaitOne(conn.ConnectionTimeout, false)) { Cleanup(tempClient); tempClient = null; throw new TimeoutException(); } #else if (!ar.AsyncWaitHandle.WaitOne(conn.ConnectionTimeout)) { Cleanup(tempClient); tempClient = null; throw new TimeoutException(); } #endif //tempClient.EndConnect(ar); zkEndpoints.CurrentEndPoint.SetAsSuccess(); break; } catch (Exception ex) { if (ex is SocketException || ex is TimeoutException) { Cleanup(tempClient); tempClient = null; zkEndpoints.CurrentEndPoint.SetAsFailure(); #if !NET_CORE LOG.WarnFormat(string.Format("Failed to connect to {0}:{1}.", zkEndpoints.CurrentEndPoint.ServerAddress.Address.ToString(), zkEndpoints.CurrentEndPoint.ServerAddress.Port.ToString())); #endif } else { throw; } } finally { #if !NET_CORE wh.Close(); #endif #if NET_CORE wh.Dispose(); #endif } }while (zkEndpoints.IsNextEndPointAvailable); if (tempClient == null) { throw KeeperException.Create(KeeperException.Code.CONNECTIONLOSS); } client = tempClient; #if !NET_CORE client.GetStream().BeginRead(incomingBuffer, 0, incomingBuffer.Length, ReceiveAsynch, incomingBuffer); #endif #if NET_CORE byte[] byteData = incomingBuffer; var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; client.GetStream().ReadAsync(incomingBuffer, 0, incomingBuffer.Length, token); tokenSource.Cancel(); MyReceiveAsynch(-1, byteData); #endif PrimeConnection(); }
/// <summary> /// Executes the compiled assembly in new process. /// Returns: process id if started now, 0 if failed, (int)ATask.ERunResult.deferred if scheduled to run later. /// </summary> /// <param name="f"></param> /// <param name="r"></param> /// <param name="args"></param> /// <param name="noDefer">Don't schedule to run later. If cannot run now, just return 0.</param> /// <param name="wrPipeName">Pipe name for ATask.WriteResult.</param> /// <param name="ignoreLimits">Don't check whether the task can run now.</param> /// <param name="runFromEditor">Starting from the Run button or menu Run command.</param> public unsafe int RunCompiled(FileNode f, Compiler.CompResults r, string[] args, bool noDefer = false, string wrPipeName = null, bool ignoreLimits = false, bool runFromEditor = false) { g1: if (!ignoreLimits && !_CanRunNow(f, r, out var running, runFromEditor)) { var ifRunning = r.ifRunning; bool same = running.f == f; if (!same) { ifRunning = r.ifRunning2 switch { EIfRunning2.cancel => EIfRunning.cancel, EIfRunning2.wait => EIfRunning.wait, EIfRunning2.warn => EIfRunning.warn, _ => (ifRunning & ~EIfRunning._restartFlag) switch { EIfRunning.cancel => EIfRunning.cancel, EIfRunning.wait => EIfRunning.wait, _ => EIfRunning.warn } }; } else if (ifRunning.Has(EIfRunning._restartFlag)) { if (runFromEditor) { ifRunning = EIfRunning.restart; } else { ifRunning &= ~EIfRunning._restartFlag; } } //AOutput.Write(same, ifRunning); switch (ifRunning) { case EIfRunning.cancel: break; case EIfRunning.wait when !noDefer: _q.Insert(0, new _WaitingTask(f, r, args)); return((int)ATask.ERunResult.deferred); //-1 case EIfRunning.restart when _EndTask(running): goto g1; default: //warn string s1 = same ? "it" : $"{running.f.SciLink}"; AOutput.Write($"<>Cannot start {f.SciLink} because {s1} is running. You may want to <+properties \"{f.IdStringWithWorkspace}\">change<> <c green>ifRunning<>, <c green>ifRunning2<>, <c green>runMode<>."); break; } return(0); } _SpUac uac = _SpUac.normal; int preIndex = 0; if (!AUac.IsUacDisabled) { //info: to completely disable UAC on Win7: gpedit.msc/Computer configuration/Windows settings/Security settings/Local policies/Security options/User Account Control:Run all administrators in Admin Approval Mode/Disabled. Reboot. //note: when UAC disabled, if our uac is System, IsUacDisabled returns false (we probably run as SYSTEM user). It's OK. var IL = AUac.OfThisProcess.IntegrityLevel; if (r.uac == EUac.inherit) { switch (IL) { case UacIL.High: preIndex = 1; break; case UacIL.UIAccess: uac = _SpUac.uiAccess; preIndex = 2; break; } } else { switch (IL) { case UacIL.Medium: case UacIL.UIAccess: if (r.uac == EUac.admin) { uac = _SpUac.admin; } break; case UacIL.High: if (r.uac == EUac.user) { uac = _SpUac.userFromAdmin; } break; case UacIL.Low: case UacIL.Untrusted: case UacIL.Unknown: //break; case UacIL.System: case UacIL.Protected: AOutput.Write($"<>Cannot run {f.SciLink}. Meta comment option <c green>uac {r.uac}<> cannot be used when the UAC integrity level of this process is {IL}. Supported levels are Medium, High and uiAccess."); return(0); //info: cannot start Medium IL process from System process. Would need another function. Never mind. } if (r.uac == EUac.admin) { preIndex = 1; } } } string exeFile, argsString; _Preloaded pre = null; byte[] taskParams = null; bool bit32 = r.prefer32bit || AVersion.Is32BitOS; if (r.notInCache) //meta role exeProgram { exeFile = Compiler.DllNameToAppHostExeName(r.file, bit32); argsString = args == null ? null : Au.Util.AStringUtil.CommandLineFromArray(args); } else { exeFile = AFolders.ThisAppBS + (bit32 ? "Au.Task32.exe" : "Au.Task.exe"); //int iFlags = r.hasConfig ? 1 : 0; int iFlags = 0; if (r.mtaThread) { iFlags |= 2; } if (r.console) { iFlags |= 4; } taskParams = Au.Util.Serializer_.SerializeWithSize(r.name, r.file, r.pdbOffset, iFlags, args, r.fullPathRefs, wrPipeName, (string)AFolders.Workspace); wrPipeName = null; if (bit32 && !AVersion.Is32BitOS) { preIndex += 3; } pre = s_preloaded[preIndex] ??= new _Preloaded(preIndex); argsString = pre.pipeName; } int pid; WaitHandle hProcess = null; bool disconnectPipe = false; try { //APerf.First(); var pp = pre?.hProcess; if (pp != null && 0 != Api.WaitForSingleObject(pp.SafeWaitHandle.DangerousGetHandle(), 0)) //preloaded process exists { hProcess = pp; pid = pre.pid; pre.hProcess = null; pre.pid = 0; } else { if (pp != null) { pp.Dispose(); pre.hProcess = null; pre.pid = 0; } //preloaded process existed but somehow ended (pid, hProcess) = _StartProcess(uac, exeFile, argsString, wrPipeName); } Api.AllowSetForegroundWindow(pid); if (pre != null) { //APerf.First(); var o = new Api.OVERLAPPED { hEvent = pre.overlappedEvent }; if (!Api.ConnectNamedPipe(pre.hPipe, &o)) { int e = ALastError.Code; if (e != Api.ERROR_PIPE_CONNECTED) { if (e != Api.ERROR_IO_PENDING) { throw new AuException(e); } var ha = stackalloc IntPtr[2] { pre.overlappedEvent, hProcess.SafeWaitHandle.DangerousGetHandle() }; int wr = Api.WaitForMultipleObjectsEx(2, ha, false, -1, false); if (wr != 0) { Api.CancelIo(pre.hPipe); throw new AuException("*start task. Preloaded task process ended"); } //note: if fails when 32-bit process, rebuild solution with platform x86 disconnectPipe = true; if (!Api.GetOverlappedResult(pre.hPipe, ref o, out _, false)) { throw new AuException(0); } } } //APerf.Next(); if (!Api.WriteFileArr(pre.hPipe, taskParams, out _)) { throw new AuException(0); } //APerf.Next(); Api.DisconnectNamedPipe(pre.hPipe); disconnectPipe = false; //APerf.NW('e'); //start preloaded process for next task. Let it wait for pipe connection. if (uac != _SpUac.admin) //we don't want second UAC consent { try { (pre.pid, pre.hProcess) = _StartProcess(uac, exeFile, argsString, null); } catch (Exception ex) { ADebug.Print(ex); } } } } catch (Exception ex) { AOutput.Write(ex); if (disconnectPipe) { Api.DisconnectNamedPipe(pre.hPipe); } hProcess?.Dispose(); return(0); } var rt = new RunningTask(f, hProcess, r.runMode != ERunMode.green); _Add(rt); return(pid); }
public void Dispose() { Timer.Elapsed -= TimerOnElapsed; WaitHandle?.Dispose(); }
public static void WaitOneAndDispose( this WaitHandle waitHandle) { waitHandle.WaitOne(); waitHandle.Dispose(); }
public void Dispose() { Channel?.Dispose(); WaitHandle?.Dispose(); }
public void Dispose() { WaitHandle.Dispose(); IsClose = true; }
public void Dispose() { _waitStart.Dispose(); }
/// <inheritdoc /> public void Dispose() { _handle.Dispose(); }