/// <summary> /// Computes draft curve silhouettes of a shape. /// </summary> /// <param name="geometry">Geometry whose silhouettes need to be computed. Can be Brep, BrepFace, Mesh, or Extrusion.</param> /// <param name="draftAngle">The draft angle in radians. Draft angle can be a positive or negative value.</param> /// <param name="pullDirection">3d direction for the mold to be pulled in, directed away from the object.</param> /// <param name="tolerance"> /// Tolerance to use for determining projecting relationships. /// Surfaces and curves that are closer than tolerance, may be treated as projecting. /// When in doubt use RhinoDoc.ModelAbsoluteTolerance. /// </param> /// <param name="angleToleranceRadians"> /// Angular tolerance to use for determining projecting relationships. /// A surface normal N that satisfies N o cameraDirection < Sin(angleToleranceRadians) may be considered projecting. /// When in doubt use RhinoDoc.ModelAngleToleranceRadians. /// </param> /// <param name="cancelToken">Computation cancellation token.</param> /// <returns>Array of silhouette curves.</returns> /// <since>7.0</since> public static Silhouette[] ComputeDraftCurve( GeometryBase geometry, double draftAngle, Vector3d pullDirection, double tolerance, double angleToleranceRadians, System.Threading.CancellationToken cancelToken ) { IntPtr const_ptr_geometry = geometry.ConstPointer(); ThreadTerminator terminator = null; if (cancelToken != System.Threading.CancellationToken.None) { terminator = new ThreadTerminator(); cancelToken.Register(terminator.RequestCancel); } IntPtr ptr_terminator = terminator == null ? IntPtr.Zero : terminator.NonConstPointer(); IntPtr ptr_silhouettes = UnsafeNativeMethods.TLC_Sillhouette3(const_ptr_geometry, draftAngle, pullDirection, tolerance, angleToleranceRadians, ptr_terminator); Silhouette[] rc = FromClassArray(ptr_silhouettes); UnsafeNativeMethods.TLC_SilhouetteArrayDelete(ptr_silhouettes); if (terminator != null) { terminator.Dispose(); } GC.KeepAlive(geometry); return(rc); }
//public static Task WaitOneAsync(this System.Threading.WaitHandle waitHandle, TimeSpan timeout) //{ // if (waitHandle == null) throw new ArgumentNullException("waitHandle"); // var Milliseconds = timeout.TotalMilliseconds; // if (Milliseconds < 1) Milliseconds = -1; // var tcs = new TaskCompletionSource<bool>(); // var rwh = System.Threading.ThreadPool.RegisterWaitForSingleObject(waitHandle, delegate { tcs.TrySetResult(true); }, null, (uint)Milliseconds, true); // var t = tcs.Task; // t.ContinueWith((antecedent) => rwh.Unregister(null)); // return t; //} public static async Task <bool> WaitOneAsync(this System.Threading.WaitHandle handle, int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { System.Threading.RegisteredWaitHandle registeredHandle = null; var tokenRegistration = default(System.Threading.CancellationTokenRegistration); try { var tcs = new TaskCompletionSource <bool>(); registeredHandle = System.Threading.ThreadPool.RegisterWaitForSingleObject( handle, (state, timedOut) => ((TaskCompletionSource <bool>)state).TrySetResult(!timedOut), tcs, millisecondsTimeout, true); tokenRegistration = cancellationToken.Register( state => ((TaskCompletionSource <bool>)state).TrySetCanceled(), tcs); return(await tcs.Task); } finally { if (registeredHandle != null) { registeredHandle.Unregister(null); } tokenRegistration.Dispose(); } }
public ShellProcessRunner(string executable, string args, System.Threading.CancellationToken cancellationToken, Action <string> outputHandler = null, bool redirectStdInput = false) { OutputHandler = outputHandler; standardOutput = new List <string>(); standardError = new List <string>(); process = new Process(); // process.StartInfo.FileName = Util.IsWindows ? "cmd.exe" : (File.Exists("/bin/zsh") ? "/bin/zsh" : "/bin/bash"); // process.StartInfo.Arguments = Util.IsWindows ? $"/c \"{executable} {args}\"" : $"-c \"{executable} {args}\""; process.StartInfo.FileName = Util.IsWindows ? executable : (File.Exists("/bin/zsh") ? "/bin/zsh" : "/bin/bash"); process.StartInfo.Arguments = Util.IsWindows ? args : $"-c \"{executable} {args}\""; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; // Process any env variables to be set that might have been set by other checkups // ie: JavaJdkCheckup sets MAUI_DOCTOR_JAVA_HOME foreach (var ev in Util.GetDoctorEnvironmentVariables()) { process.StartInfo.Environment[ev.Key] = ev.Value?.ToString(); } if (redirectStdInput) { process.StartInfo.RedirectStandardInput = true; } process.OutputDataReceived += (s, e) => { if (e.Data != null) { standardOutput.Add(e.Data); OutputHandler?.Invoke(e.Data); } }; process.ErrorDataReceived += (s, e) => { if (e.Data != null) { standardError.Add(e.Data); OutputHandler?.Invoke(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (cancellationToken != System.Threading.CancellationToken.None) { cancellationToken.Register(() => { try { process.Kill(); } catch { } try { process?.Dispose(); } catch { } }); } }
bool RunAdb(AdbToolSettings settings, ProcessArgumentBuilder builder, System.Threading.CancellationToken cancelToken, out List <string> output) { var p = RunProcess(settings, builder, new ProcessSettings { RedirectStandardOutput = true, }); if (cancelToken != System.Threading.CancellationToken.None) { cancelToken.Register(() => { try { p.Kill(); } catch { } }); } p.WaitForExit(); output = p.GetStandardOutput().ToList(); // Log out the lines anyway foreach (var line in output) { context.Log.Write(Core.Diagnostics.Verbosity.Verbose, Core.Diagnostics.LogLevel.Information, line); } return(p.GetExitCode() == 0); }
/// <summary> /// Returns the HTTP response. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param> /// <returns></returns> public virtual async System.Threading.Tasks.Task <IWebResponseData> GetResponseAsync(System.Threading.CancellationToken cancellationToken) { try { using (cancellationToken.Register(() => this.Abort(), useSynchronizationContext: false)) { var response = await _request.GetResponseAsync().ConfigureAwait(false) as HttpWebResponse; return(new HttpWebRequestResponseData(response)); } } catch (WebException webException) { // After HttpWebRequest.Abort() is called, GetResponseAsync throws a WebException. // If request has been cancelled using cancellationToken, wrap the // WebException in an OperationCancelledException. if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(webException.Message, webException, cancellationToken); } var errorResponse = webException.Response as HttpWebResponse; if (errorResponse != null) { throw new HttpErrorResponseException(webException.Message, webException, new HttpWebRequestResponseData(errorResponse)); } throw; } }
public static async Task <Polyline> DrawPolylineAsync(SceneView sceneView, System.Threading.CancellationToken cancellationToken) { var tcs = new TaskCompletionSource <Polyline>(); PolylineBuilder polylineBuilder = new PolylineBuilder(sceneView.SpatialReference); polylineBuilder.AddPart(new MapPoint[] { }); var sketchlayer = CreateSketchLayer(sceneView); Graphic lineGraphic = new Graphic() { Symbol = DefaultLineSymbol }; Graphic lineMoveGraphic = new Graphic() { Symbol = DefaultLineMoveSymbol }; sketchlayer.Graphics.AddRange(new Graphic[] { lineGraphic, lineMoveGraphic }); Action cleanupEvents = SetUpHandlers(sceneView, (p) => //On mouse move, move completion line around { if (p != null && polylineBuilder.Parts.Count > 0 && polylineBuilder.Parts[0].Count > 0) { lineMoveGraphic.Geometry = new Polyline(new MapPoint[] { polylineBuilder.Parts[0].Last().EndPoint, p }); } }, (p) => //On tap add a vertex { if (p != null) { polylineBuilder.AddPoint(p); if (polylineBuilder.Parts.Count > 0 && polylineBuilder.Parts[0].Count >= 1) { lineGraphic.Geometry = polylineBuilder.ToGeometry(); } } }, (p) => //View tapped - completes task and returns point { tcs.SetResult(polylineBuilder.ToGeometry()); }); Action cleanup = () => { cleanupEvents(); sceneView.GraphicsOverlays.Remove(sketchlayer); }; cancellationToken.Register(() => tcs.SetCanceled()); Polyline result = null; try { result = await tcs.Task; } finally { cleanup(); } return(result); }
public RefreshDataModule( TimeSpan refreshInterval, ISensorDataProvider sensorDataProvider, SensorDataCache cache, CancellationToken cancelRefreshSensorsToken) { this.RefreshInterval = refreshInterval; this.Cache = cache; this.SensorDataProvider = sensorDataProvider; this.Report = new UpdateSensorDataReport(); RefreshSensorsData(); this.RefreshTimer = new Timer { AutoReset = true, Interval = this.RefreshInterval.TotalMilliseconds }; this.RefreshTimer.Elapsed += RefreshTimer_Elapsed; this.RefreshTimer.Start(); cancelRefreshSensorsToken.Register( () => { this.RefreshTimer.Stop(); this.RefreshTimer.Elapsed -= RefreshTimer_Elapsed; this.Report.LogState(updateStopped: true); } ); }
public DragDropForm(string dropPath, string dropText, System.Threading.CancellationToken token) { var appTheme = GetAppTheme(); this.FormBorderStyle = FormBorderStyle.None; this.ShowInTaskbar = false; this.MaximizeBox = false; this.MinimizeBox = false; this.Text = "Files"; this.BackColor = appTheme switch { Windows.UI.Xaml.ElementTheme.Light => System.Drawing.Color.White, _ => System.Drawing.Color.Black }; this.Opacity = 0.5; this.TopMost = true; this.DragOver += DragDropForm_DragOver; this.DragDrop += DragDropForm_DragDrop; this.DragLeave += DragDropForm_DragLeave; this.AllowDrop = true; var label = new Label(); label.AutoSize = false; label.Font = new System.Drawing.Font("Segoe UI", 24); label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; label.ForeColor = appTheme switch { Windows.UI.Xaml.ElementTheme.Light => System.Drawing.Color.Black, _ => System.Drawing.Color.White }; label.Dock = DockStyle.Fill; label.Text = dropText; this.Controls.Add(label); this.dropPath = dropPath; // Create window over Files window this.StartPosition = FormStartPosition.Manual; var Handle = Vanara.PInvoke.User32.WindowFromPoint(Cursor.Position); Vanara.PInvoke.User32.GetWindowRect(Handle, out var lpRect); this.Size = new System.Drawing.Size(lpRect.Width, lpRect.Height); this.Location = new System.Drawing.Point(lpRect.Location.X, lpRect.Location.Y); token.Register(() => { if (this.IsHandleCreated) { // If another window is created, close this one this.Invoke(new InvokeDelegate(() => this.Close())); } }); this.HandleCreated += DragDropForm_HandleCreated; }
public ShellProcessRunner(string executable, string args, System.Threading.CancellationToken cancellationToken, string workingDir = null, Action <string> outputHandler = null) { OutputHandler = outputHandler; standardOutput = new List <string>(); standardError = new List <string>(); process = new Process(); // process.StartInfo.FileName = Util.IsWindows ? "cmd.exe" : (File.Exists("/bin/zsh") ? "/bin/zsh" : "/bin/bash"); // process.StartInfo.Arguments = Util.IsWindows ? $"/c \"{executable} {args}\"" : $"-c \"{executable} {args}\""; process.StartInfo.FileName = Util.IsWindows ? executable : (File.Exists("/bin/zsh") ? "/bin/zsh" : "/bin/bash"); process.StartInfo.Arguments = Util.IsWindows ? args : $"-c \"{executable} {args}\""; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardError = true; if (!string.IsNullOrEmpty(workingDir)) { process.StartInfo.WorkingDirectory = workingDir; } process.OutputDataReceived += (s, e) => { if (e.Data != null) { standardOutput.Add(e.Data); Console.WriteLine(e.Data); OutputHandler?.Invoke(e.Data); } }; process.ErrorDataReceived += (s, e) => { if (e.Data != null) { standardError.Add(e.Data); Console.WriteLine(e.Data); OutputHandler?.Invoke(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (cancellationToken != System.Threading.CancellationToken.None) { cancellationToken.Register(() => { try { process.Kill(); } catch { } }); } }
internal System.Threading.Tasks.Task <Hint> GetHintAsync(System.Threading.CancellationToken cancellationToken) { Debug.Assert(_hintCompletion == null); var hintCompletion = _hintCompletion = new System.Threading.Tasks.TaskCompletionSource <Hint>(); _hintCancellationTokenRegistration = cancellationToken.Register(() => { hintCompletion.TrySetCanceled(cancellationToken); _hintCompletion = null; }); return(hintCompletion.Task); }
public ProcessRunner(FileInfo executable, ProcessArgumentBuilder builder, DirectoryInfo workingDirectory, System.Threading.CancellationToken cancelToken, bool redirectStandardInput = false, Action <ProcessStartInfo> startInfo = null) { standardOutput = new List <string>(); standardError = new List <string>(); //* Create your Process process = new Process(); process.StartInfo.FileName = executable.FullName; process.StartInfo.Arguments = builder.ToString(); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; if (workingDirectory != null) { process.StartInfo.WorkingDirectory = workingDirectory.FullName; } if (redirectStandardInput) { process.StartInfo.RedirectStandardInput = true; } startInfo?.Invoke(process.StartInfo); process.OutputDataReceived += (s, e) => { if (e.Data != null) { standardOutput.Add(e.Data); } }; process.ErrorDataReceived += (s, e) => { if (e.Data != null) { standardError.Add(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (cancelToken != System.Threading.CancellationToken.None) { cancelToken.Register(() => { try { process.Kill(); } catch { } }); } }
public ProcessRunner(FileInfo executable, ProcessArgumentBuilder builder, System.Threading.CancellationToken cancelToken, bool redirectStandardInput = false) { standardOutput = new List <string>(); standardError = new List <string>(); //* Create your Process process = new Process(); process.StartInfo.FileName = executable.FullName; process.StartInfo.Arguments = builder.ToString(); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; // Process any env variables to be set that might have been set by other checkups // ie: JavaJdkCheckup sets MAUI_DOCTOR_JAVA_HOME foreach (var ev in Util.GetDoctorEnvironmentVariables()) { process.StartInfo.Environment[ev.Key] = ev.Value?.ToString(); } if (redirectStandardInput) { process.StartInfo.RedirectStandardInput = true; } process.OutputDataReceived += (s, e) => { if (e.Data != null) { standardOutput.Add(e.Data); } }; process.ErrorDataReceived += (s, e) => { if (e.Data != null) { standardError.Add(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (cancelToken != System.Threading.CancellationToken.None) { cancelToken.Register(() => { try { process.Kill(); } catch { } }); } }
/// <summary> /// Start a <see cref="System.Threading.Timer"/> that sends pings to the child process to keep it from shutting down. /// </summary> public void StartChildPinger(System.Threading.CancellationToken cancellationToken) { var timer = new System.Threading.Timer(state => { using (var outgoingRequestPipe = new NamedPipeClientStream(_serverName, _pipeNamePrefix + Constants.PingPipeNameSuffix, PipeDirection.Out)) { outgoingRequestPipe.Connect(); } }, null, Constants.PingIntervalMilliseconds, Constants.PingIntervalMilliseconds); cancellationToken.Register(() => timer.Dispose()); //No need to store the timer in a private field; it will not get garbage collected while it's running. }
public static async Task <MapPoint> DrawPointAsync(MapView sceneView, System.Threading.CancellationToken cancellationToken) { var tcs = new TaskCompletionSource <MapPoint>(); var sketchlayer = CreateSketchLayer(sceneView); sketchlayer.Opacity = .5; Graphic pointGraphic = null; Action cleanupEvents = SetUpHandlers(sceneView, (p) => //On mouse move move graphic around { if (p != null) { if (pointGraphic == null) { pointGraphic = new Graphic(p, DefaultMarkerSymbol); sketchlayer.Graphics.Add(pointGraphic); } else { pointGraphic.Geometry = p; } } }, (p) => //View tapped - completes task and returns point { tcs.SetResult(p); } , null); Action cleanup = () => { cleanupEvents(); sceneView.GraphicsOverlays.Remove(sketchlayer); }; cancellationToken.Register(() => tcs.SetCanceled()); MapPoint result = null; try { result = await tcs.Task; } finally { cleanup(); } return(result); }
internal Task Run(IEnumerable <TestCase> tests, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (IsRunning) { throw new InvalidOperationException("Test run already running"); } token = new TestRunCancellationToken(); if (cancellationToken.CanBeCanceled) { cancellationToken.Register(() => token.Cancel()); } return(System.Threading.Tasks.Task.Run(() => { new TestExecutionManager().RunTests(tests, this, this, token); token = null; })); }
protected override IEnumerable <Ide.FindInFiles.MemberReference> GetReferences(Tuple <ResolutionContext, DSymbol> tup, System.Threading.CancellationToken token) { var ctxt = tup.Item1; ctxt.CancelOperation = false; token.Register(() => ctxt.CancelOperation = true); var mr = tup.Item2; var referencedNode = mr.Definition; // Slightly hacky: To keep highlighting the id of e.g. a NewExpression, take the ctor's parent node (i.e. the class node) if (referencedNode is DMethod && ((DMethod)referencedNode).SpecialType == DMethod.MethodType.Constructor) { mr = mr.Base as DSymbol; if (mr == null) { yield break; } referencedNode = mr.Definition; } var parseCache = Document.HasProject ? (Document.Project as AbstractDProject).ParseCache : DCompilerService.Instance.GetDefaultCompiler().GenParseCacheView(); IEnumerable <ISyntaxRegion> refs = null; try{ refs = D_Parser.Refactoring.ReferencesFinder.Scan(SyntaxTree, referencedNode, ctxt); } catch (Exception ex) { LoggingService.LogInfo("Error during highlighting usages", ex); } if (refs != null) { foreach (var sym in refs) { yield return(new Ide.FindInFiles.MemberReference(sym, new ICSharpCode.NRefactory.TypeSystem.DomRegion(Document.FileName, sym.Location.Line, sym.Location.Column, sym.EndLocation.Line, sym.EndLocation.Column), Document.Editor.LocationToOffset(sym.Location.Line, sym.Location.Column), sym.EndLocation.Column - sym.Location.Column)); } } }
public NetworkClientWrapper(NetworkProtocol protocol, IPEndPoint endPoint, System.Threading.CancellationToken cancellationToken) { isUdp = protocol == NetworkProtocol.Udp; if (isUdp) { udpClient = new UdpClient { ExclusiveAddressUse = false }; udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.Client.Bind(endPoint); } else { tcpListener = new TcpListener(endPoint); tcpListener.Start(); cancellationToken.Register(() => tcpListener.Stop()); } }
/// <summary> /// Compute silhouettes of a shape for a perspective projection. /// </summary> /// <param name="geometry">Geometry whose silhouettes need to be computed. Can be Brep, BrepFace, Mesh, or Extrusion.</param> /// <param name="silhouetteType">Types of silhouette to compute.</param> /// <param name="perspectiveCameraLocation">Location of perspective camera.</param> /// <param name="tolerance">Tolerance to use for determining projecting relationships. /// Surfaces and curves that are closer than tolerance, may be treated as projecting. /// When in doubt use RhinoDoc.ModelAbsoluteTolerance.</param> /// <param name="angleToleranceRadians">Angular tolerance to use for determining projecting relationships. /// A surface normal N that satisfies N o cameraDirection < Sin(angleToleranceRadians) may be considered projecting. /// When in doubt use RhinoDoc.ModelAngleToleranceRadians.</param> /// <param name="clippingPlanes">Optional collection of clipping planes.</param> /// <param name="cancelToken">Computation cancellation token.</param> /// <returns>Array of silhouette curves.</returns> public static Silhouette[] Compute( GeometryBase geometry, SilhouetteType silhouetteType, Point3d perspectiveCameraLocation, double tolerance, double angleToleranceRadians, IEnumerable <Plane> clippingPlanes, System.Threading.CancellationToken cancelToken) { IntPtr const_ptr_geometry = geometry.ConstPointer(); Plane[] planes = null; int plane_count = 0; if (clippingPlanes != null) { List <Plane> p = new List <Plane>(clippingPlanes); plane_count = p.Count; planes = p.ToArray(); } ThreadTerminator terminator = null; IntPtr ptr_terminator = IntPtr.Zero; if (cancelToken != System.Threading.CancellationToken.None) { terminator = new ThreadTerminator(); ptr_terminator = terminator.NonConstPointer(); cancelToken.Register(terminator.RequestCancel); } UnsafeNativeMethods.SilEventType s = (UnsafeNativeMethods.SilEventType)silhouetteType; IntPtr ptr_silhouettes = UnsafeNativeMethods.TLC_Sillhouette2(const_ptr_geometry, s, perspectiveCameraLocation, tolerance, angleToleranceRadians, planes, plane_count, ptr_terminator); Silhouette[] rc = FromClassArray(ptr_silhouettes); UnsafeNativeMethods.TLC_SilhouetteArrayDelete(ptr_silhouettes); if (terminator != null) { terminator.Dispose(); } GC.KeepAlive(geometry); return(rc); }
/// <summary>You must call Disable on the reporter output if it's not null when you are done with it. It will NOT clean itself. /// You should call Dispose on the terminator if it's not null, because that will keep it alive for the time of the computation.</summary> internal static void MarshalProgressAndCancelToken(System.Threading.CancellationToken cancel, IProgress <double> progress, out IntPtr ptrTerminator, out int progressInt, out ProgressReporter reporter, out ThreadTerminator terminator) { reporter = null; progressInt = 0; if (progress != null) { reporter = new ProgressReporter(progress); progressInt = reporter.SerialNumber; reporter.Enable(); } terminator = null; if (cancel != System.Threading.CancellationToken.None) { terminator = new ThreadTerminator(); cancel.Register(terminator.RequestCancel); } ptrTerminator = terminator == null ? IntPtr.Zero : terminator.NonConstPointer(); }
static StackObject *Register_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Action @callback = (System.Action) typeof(System.Action).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Threading.CancellationToken instance_of_this_method = (System.Threading.CancellationToken) typeof(System.Threading.CancellationToken).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.Register(@callback); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
bool RunAdb(AdbToolSettings settings, ProcessArgumentBuilder builder, System.Threading.CancellationToken cancelToken, out List <string> output) { var adbToolPath = this.GetToolPath(settings); if (!context.FileSystem.Exist(adbToolPath)) { throw new System.IO.FileNotFoundException("Could not find adb", settings.ToolPath.FullPath); } var p = RunProcess(settings, builder, new ProcessSettings { RedirectStandardOutput = true, }); if (cancelToken != System.Threading.CancellationToken.None) { cancelToken.Register(() => { try { p.Kill(); } catch { } }); } p.WaitForExit(); output = p.GetStandardOutput().ToList(); // Log out the lines anyway foreach (var line in output) { context.Log.Write(Core.Diagnostics.Verbosity.Verbose, Core.Diagnostics.LogLevel.Information, line.Replace("{", "{{").Replace("}", "}}")); } var error = output?.FirstOrDefault(o => o.StartsWith("error:", StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrEmpty(error)) { throw new Exception(error); } return(p.GetExitCode() == 0); }
/// <summary> /// /// </summary> /// <param name="interval"></param> /// <param name="portion"></param> /// <param name="cancellationToken"></param> public virtual void StartScan(TimeSpan interval, int portion, System.Threading.CancellationToken cancellationToken = default) { if (_started) { return; } _started = true; //this.Recipient = recipient ?? throw new ArgumentException("Пустой адрес получателя сообщений.", nameof(recipient)); _interval = interval; _portion = portion; _cancellationToken = cancellationToken; _cancellationToken.Register(() => { OnCancel(); }); _queryTimer.Interval = interval.TotalMilliseconds; _queryTimer.Start(); }
public void StartReadingData() { cws = new System.Net.WebSockets.ClientWebSocket(); token.Register(OnCancel); cws.ConnectAsync(new Uri("wss://ws.bitstamp.net"), token).Wait(); string msgSubscribe = String.Format("{{\"event\": \"bts:subscribe\",\"data\": {{\"channel\": \"order_book_{0}\"}}}}\r\n", currencyPair); string msgUnubscribe = String.Format("{{\"event\": \"bts:unsubscribe\",\"data\": {{\"channel\": \"order_book_{0}\"}}}}\r\n", currencyPair); cws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(msgSubscribe)), System.Net.WebSockets.WebSocketMessageType.Binary, true, token); ReadMsgSync(token); string msg = ReadMsgSync(token); cws.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(msgUnubscribe)), System.Net.WebSockets.WebSocketMessageType.Text, true, token); JsonData data = System.Text.Json.JsonSerializer.Deserialize <JsonData>(msg); Bids.Clear(); Asks.Clear(); MoveJsonDataToTransactions(data); thread = new System.Threading.Thread(ReadAndUpdateData); thread.Start(); }
public override async Task Speak(string text, System.Threading.CancellationToken cancellationToken) { var utterance = new AVSpeechUtterance(text); var source = await utterances.GetOrAddAsync(utterance, (u) => new TaskCompletionSource <string>()); cancellationToken.Register(() => { if (synth.Speaking) { synth.StopSpeaking(AVSpeechBoundary.Immediate); } source.TrySetCanceled(); }); synth.SpeakUtterance(utterance); try { await source.Task; } finally { await utterances.RemoveAsync(utterance); } }
public override async Task Speak(string text, System.Threading.CancellationToken ct) { await initialized.Task; string key = DateTime.UtcNow.Ticks.ToString(); var source = await sources.GetOrAddAsync(key, k => new TaskCompletionSource <string>()); ct.Register(() => { if (tts.IsSpeaking) { tts.Stop(); } source.TrySetCanceled(); }); tts.Speak(text, QueueMode.Add, null, key); try { await source.Task; } finally { await sources.RemoveAsync(key); } }
static Task Delay(int delayTime, System.Threading.CancellationToken token) { TaskCompletionSource <object> tcs = new TaskCompletionSource <object>(); if (delayTime < 0) { throw new ArgumentOutOfRangeException("Delay time cannot be under 0"); } System.Threading.Timer timer = null; timer = new System.Threading.Timer(p => { timer.Dispose(); //stop the timer tcs.TrySetResult(null); //timer expired, attempt to move task to the completed state. }, null, delayTime, System.Threading.Timeout.Infinite); token.Register(() => { timer.Dispose(); //stop the timer tcs.TrySetCanceled(); //attempt to mode task to canceled state }); return(tcs.Task); }
/// <summary> /// This is an internal method called from ReadInternal method. /// </summary> /// <param name="buffer">The byte array, passed to Read method.</param> /// <param name="offset">The offset in the buffer array to begin writing.</param> /// <param name="count">The number of bytes to read.</param> /// <param name="timeout">Milliseconds before a time-out occurs.</param> /// <param name="ct">A cancellation_token will be signaled by user cancellation.</param> /// <returns> /// The result of Task contains the length of bytes read. This may be less than count. /// </returns> private Task <int> ReadPartial( Windows.Storage.Streams.IBuffer buffer, int offset, int count, int timeout, System.Threading.CancellationToken ct ) { // Buffer check. if ((int)buffer.Length < (offset + count)) { throw new ArgumentException("Capacity of buffer is not enough."); } var inputStream = this.cdcData.BulkInPipes[0].InputStream; var reader = new Windows.Storage.Streams.DataReader(inputStream); return(Task.Run(async() => { // CancellationTokenSource to cancel tasks. var cancellationTokenSource = new System.Threading.CancellationTokenSource(); // LoadAsync task. var loadTask = reader.LoadAsync((uint)count).AsTask <uint>(cancellationTokenSource.Token); // A timeout task that completes after the specified delay. var timeoutTask = Task.Delay(timeout == Constants.InfiniteTimeout ? System.Threading.Timeout.Infinite : timeout, cancellationTokenSource.Token); // Cancel tasks by user's cancellation. bool canceledByUser = false; ct.Register(() => { canceledByUser = true; cancellationTokenSource.Cancel(); }); // Wait tasks. Task[] tasks = { loadTask, timeoutTask }; var signaledTask = await Task.WhenAny(tasks); // Check the task status. bool loadCompleted = signaledTask.Equals(loadTask) && loadTask.IsCompleted && !loadTask.IsCanceled; bool isTimeout = signaledTask.Equals(timeoutTask) && timeoutTask.IsCompleted && !timeoutTask.IsCanceled; // Cancel all incomplete tasks. cancellationTokenSource.Cancel(); int loadedCount = 0; if (loadCompleted) { loadedCount = (int)loadTask.Result; } else if (isTimeout) { // Timeout. throw new System.TimeoutException("ReadPartial was timeout."); } else if (canceledByUser) { throw new OperationCanceledException("ReadPartial was canceled."); } if (loadedCount > 0) { var readBuffer = reader.ReadBuffer((uint)loadedCount); System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.CopyTo(readBuffer, 0, buffer, (uint)offset, (uint)loadedCount); } return loadedCount; })); }
public override Task <int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { cancellationToken.Register(() => disposeCompletingSource.TrySetCanceled()); return(disposeCompletingSource.Task); }
public async Task <JobStatus> RunSendNewsEmailsJob(int jobId, System.Threading.CancellationToken token, IProgress <JobStatus> progress) { var sw = System.Diagnostics.Stopwatch.StartNew(); var job = await _jobRepository.GetByIdAsync(jobId); var jobDetails = JsonConvert.DeserializeObject <JobSendNewsEmails>(job.SerializedParameters); _logger.LogInformation("Job {JobId}: {JobType} to send emails for post {NewsPostId}", job.Id, job.JobType, jobDetails.NewsPostId); token.Register(() => { _logger.LogWarning("Job {JobId}: {JobType} to send emails for post {NewsPostId} cancelled after {Elapsed} ms", job.Id, job.JobType, sw?.Elapsed.TotalMilliseconds); }); var post = await _newsPostRepository.GetByIdAsync(jobDetails.NewsPostId); if (string.IsNullOrEmpty(post.CategoryName)) { var category = await _newsCategoryRepository.GetByIdAsync(post.CategoryId); post.CategoryName = category?.Name; } if (post == null) { await _jobRepository.UpdateStatusAsync(jobId, $"Could not locate news post id {jobDetails.NewsPostId} to send emails."); return(new JobStatus { Complete = true, Error = true, Status = $"Could not locate news post id {jobDetails.NewsPostId} to send emails." }); } var subscribedUserIds = (await _userRepository .GetNewsSubscribedUserIdsAsync(job.SiteId)).ToList(); if (subscribedUserIds.Count == 0) { await _jobRepository.UpdateStatusAsync(jobId, "No subscribed users to send emails to."); return(new JobStatus { Complete = true, Error = false, Status = "No subscribed users to send emails to." }); } int sentEmails = 0; var lastUpdate = sw.Elapsed.TotalSeconds; await _jobRepository.UpdateStatusAsync(jobId, $"Preparing to email {subscribedUserIds.Count} users..."); progress?.Report(new JobStatus { PercentComplete = 0, Status = $"Preparing to email {subscribedUserIds.Count} users..." }); var directEmailDetails = new DirectEmailDetails(jobDetails.SiteName) { DirectEmailSystemId = "NewsPost", IsBulk = true, SendingUserId = await _userRepository.GetSystemUserId() }; directEmailDetails.Tags.Add("Category", post.CategoryName); directEmailDetails.Tags.Add("PostLink", jobDetails.PostLink); directEmailDetails.Tags.Add("PostTitle", post.Title); directEmailDetails.Tags.Add("Summary", post.EmailSummary); directEmailDetails.Tags.Add("UnsubscribeLink", jobDetails.SiteMcLink); foreach (var userId in subscribedUserIds) { if (token.IsCancellationRequested) { await _jobRepository.UpdateStatusAsync(jobId, $"Cancelling after {sentEmails}/{subscribedUserIds.Count} emails in {sw?.Elapsed.TotalMilliseconds} ms."); return(new JobStatus { PercentComplete = sentEmails * 100 / subscribedUserIds.Count, Complete = true, Status = $"Cancelling after {sentEmails}/{subscribedUserIds.Count} emails in {sw?.Elapsed.TotalMilliseconds} ms." }); } directEmailDetails.ToUserId = userId; try { var history = await _emailService.SendDirectAsync(directEmailDetails); if (history.Successful) { sentEmails++; } else { _logger.LogWarning("Unable to send newsletter notification email to user {UserId}", userId); } } catch (Exception ex) { _logger.LogWarning("Unable to send newsletter notification email to user {UserId}: {ErrorMessage}", userId, ex.Message); } if (sw.Elapsed.TotalSeconds > lastUpdate + 5) { await _jobRepository.UpdateStatusAsync(jobId, $"Sent {sentEmails}/{subscribedUserIds.Count} emails..."); progress?.Report(new JobStatus { PercentComplete = sentEmails * 100 / subscribedUserIds.Count, Status = $"Sent {sentEmails}/{subscribedUserIds.Count} emails..." }); lastUpdate = sw.Elapsed.TotalSeconds; } } await _jobRepository.UpdateStatusAsync(jobId, $"Sent emails to {sentEmails}/{subscribedUserIds.Count} users in {sw?.Elapsed.TotalMilliseconds} ms."); return(new JobStatus { PercentComplete = sentEmails * 100 / subscribedUserIds.Count, Complete = true, Status = $"Sent emails to {sentEmails}/{subscribedUserIds.Count} users in {sw?.Elapsed.TotalMilliseconds} ms." }); }