private async void StartInternal(CancellationToken cancellationToken) { byte[] buffer = new byte[256]; var commandBuilder = new StringBuilder(); var serverStream = new NamedPipeServerStream(this.PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0); using (cancellationToken.Register(() => serverStream.Close())) { while (!cancellationToken.IsCancellationRequested) { await Task.Factory.FromAsync(serverStream.BeginWaitForConnection, serverStream.EndWaitForConnection, TaskCreationOptions.None); int read = await serverStream.ReadAsync(buffer, 0, buffer.Length); commandBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read)); while (!serverStream.IsMessageComplete) { read = serverStream.Read(buffer, 0, buffer.Length); commandBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read)); } var response = this.HandleReceivedCommand(commandBuilder.ToString()); var responseBytes = Encoding.ASCII.GetBytes(response); serverStream.Write(responseBytes, 0, responseBytes.Length); serverStream.WaitForPipeDrain(); serverStream.Disconnect(); commandBuilder.Clear(); } } }
public Task SearchAsync(string searchPattern, FileSearchMode mode, int count, IFileCollection files, CancellationToken cancellationToken) { if (String.IsNullOrEmpty(searchPattern)) { files.Clear(); foreach (string filePath in pinStateService.GetList()) files.Add(Path.GetFileNameWithoutExtension(filePath), filePath, true); if (lastCancellation != null) { lastCancellation.Cancel(); lastCancellation = null; } return Task.FromResult(true); } if (cancellationToken.IsCancellationRequested) return Async.CompletedTask; lastCancellation = new CancellationTokenSource(); cancellationToken.Register(() => lastCancellation.Cancel()); Task result = innerService.SearchAsync(searchPattern, mode, count, files, lastCancellation.Token); return result; }
public static void CancellationTokenRegister_Exceptions() { CancellationToken token = new CancellationToken(); Assert.Throws<ArgumentNullException>(() => token.Register(null)); Assert.Throws<ArgumentNullException>(() => token.Register(null, false)); Assert.Throws<ArgumentNullException>(() => token.Register(null, null)); }
public Task Start(CancellationToken cancellationToken) { var completion = new TaskCompletionSource<bool>(); cancellationToken.Register(() => ProcessExtensions.Terminate(_process)); // Hook up the events. We don't hook up OutputDataReceived, because that wants to treat the data as strings; we need binary. _process.ErrorDataReceived += (sender, e) => OnErrorDataReceived(new ErrorDataReceivedEventArgs(e.Data)); _process.Exited += (sender, e) => { _process.WaitForExit(1000); _process.StandardOutput.Close(); if (_process.ExitCode == 0) completion.SetResult(true); else if (cancellationToken.IsCancellationRequested) completion.SetCanceled(); else completion.SetException(new CodecProcessFailedException(_process.ExitCode)); }; _process.Start(); _process.PriorityClass = ProcessPriorityClass.BelowNormal; _process.BeginErrorReadLine(); return completion.Task; }
public override Task <PaymentProviderBeginPaymentResponse> BeginPaymentAsync(BeginPaymentRequest request, System.Threading.CancellationToken cancellation) { var tcs = new TaskCompletionSource <PaymentProviderBeginPaymentResponse>(); try { var pec = new ir.shaparak.pec.EShopService(); pec.PinPaymentRequestCompleted += new PinPaymentRequestCompletedEventHandler((sender, args) => { if (args.Error != null) { tcs.TrySetException(args.Error); } else if (!args.Cancelled) { try { var result = new PaymentProviderBeginPaymentResponse <AyandehBankTranStatus>(Now); result.ProviderType = this.ProviderType; result.Code = args.authority; result.SendData.Add(BankCodeArgName, args.authority.ToString()); result.Status = args.status; result.Succeeded = (args.status == 0 && args.authority != -1); result.GatewayUrl = Config.GatewayUrl + $"?{BankCodeArgName}={args.authority}"; result.SendMethod = Config.GatewayMethod; tcs.SetResult(result); } catch (Exception ex) { tcs.TrySetException(ex); } } else { tcs.SetCanceled(); } pec.Dispose(); }); var orderid = SafeClrConvert.ToInt32(request.PaymentCode); var pay = SafeClrConvert.ToInt32(request.Amount); byte pecStatus = 0; long auth = 0; cancellation.Register(() => pec.CancelAsync(request.PaymentCode)); pec.PinPaymentRequestAsync(Config.Credentials.Pin, pay, orderid, (string.IsNullOrEmpty(request.ReturnUrl) ? Config.CallbackUrl : request.ReturnUrl), auth, pecStatus, request.PaymentCode); } catch (Exception e) { tcs.SetException(e); } return(tcs.Task); }
public void Start() { _cancellationToken = QueryRequest.CancellationToken; RowSource.RowSourceChanged += RowSourceChanged; _cancellationToken.Register(() => RowSource.RowSourceChanged -= RowSourceChanged); Run(); }
public static Task<ProcessResults> RunAsync(ProcessStartInfo processStartInfo, CancellationToken cancellationToken) { if (processStartInfo == null) { throw new ArgumentNullException("processStartInfo"); } // force some settings in the start info so we can capture the output processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; processStartInfo.CreateNoWindow = true; var tcs = new TaskCompletionSource<ProcessResults>(); var standardOutput = new List<string>(); var standardError = new List<string>(); var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true, }; process.OutputDataReceived += (sender, args) => { if (args.Data != null) { standardOutput.Add(args.Data); } }; process.ErrorDataReceived += (sender, args) => { if (args.Data != null) { standardError.Add(args.Data); } }; process.Exited += (sender, args) => tcs.TrySetResult(new ProcessResults(process, standardOutput, standardError)); cancellationToken.Register(() => { tcs.TrySetCanceled(); process.CloseMainWindow(); }); cancellationToken.ThrowIfCancellationRequested(); if (process.Start() == false) { tcs.TrySetException(new InvalidOperationException("Failed to start process")); } process.BeginOutputReadLine(); process.BeginErrorReadLine(); return tcs.Task; }
public static TT.Task ToTask(this T.CancellationToken ct) { var tcs = new TT.TaskCompletionSource <bool>(); ct.Register(() => tcs.SetResult(false)); return(tcs.Task); }
public async Task<WebSocket> ConnectAsync(HttpWebRequest request, CancellationToken cancellationToken) { HttpWebResponse response; using (cancellationToken.Register(request.Abort)) { response = (HttpWebResponse)await request.GetResponseAsync(); } InspectResponse?.Invoke(response); // TODO: Validate handshake HttpStatusCode statusCode = response.StatusCode; if (statusCode != HttpStatusCode.SwitchingProtocols) { response.Dispose(); throw new InvalidOperationException("Incomplete handshake, invalid status code: " + statusCode); } // TODO: Validate Sec-WebSocket-Key/Sec-WebSocket-Accept string subProtocol = response.Headers[Constants.Headers.SecWebSocketProtocol]; if (!string.IsNullOrEmpty(subProtocol) && !SubProtocols.Contains(subProtocol, StringComparer.OrdinalIgnoreCase)) { throw new InvalidOperationException("Incomplete handshake, the server specified an unknown sub-protocol: " + subProtocol); } var stream = response.GetResponseStream(); return CommonWebSocket.CreateClientWebSocket(stream, subProtocol, KeepAliveInterval, ReceiveBufferSize, UseZeroMask); }
public RSessionEvaluation(IReadOnlyList<IRContext> contexts, IRExpressionEvaluator evaluator, CancellationToken ct) { Contexts = contexts; _evaluator = evaluator; _tcs = new TaskCompletionSource<object>(); _ct = ct; ct.Register(() => _tcs.TrySetCanceled()); }
/// <summary> /// If AutoSaveChanges is set this method will auto commit changes /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> protected virtual Task<int> SaveChanges(CancellationToken cancellationToken) { var source = new TaskCompletionSource<int>(); if (AutoSaveChanges) { var registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { if (cancellationToken.IsCancellationRequested) { source.SetCanceled(); return source.Task; } registration = cancellationToken.Register(CancelIgnoreFailure); } try { return _uow.SaveChangesAsync(cancellationToken); } catch (Exception e) { source.SetException(e); } finally { registration.Dispose(); } } return source.Task; }
/// <summary> /// Get's the primary workspace asynchronously. /// </summary> public static Task<Workspace> GetWorkspaceAsync(CancellationToken cancellationToken = default(CancellationToken)) { using (s_registryGate.DisposableWrite()) { if (s_primaryWorkspace != null) { return Task<Workspace>.FromResult(s_primaryWorkspace); } else { var taskSource = new TaskCompletionSource<Workspace>(); if (cancellationToken.CanBeCanceled) { try { var registration = cancellationToken.Register(() => { taskSource.TrySetCanceled(); }); taskSource.Task.ContinueWith(_ => registration.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } catch { } } s_primaryWorkspaceTaskSourceList.Add(taskSource); return taskSource.Task; } } }
public async Task Run(CancellationToken token) { var tcs = new TaskCompletionSource<bool>(); token.Register(() => { this.receiver.Close(); tcs.SetResult(true); }); this.receiver.OnMessageAsync(rq => this.Respond(rq, this.responseFunction), new OnMessageOptions { AutoComplete = false }); await tcs.Task; }
public GeolocationSingleUpdateDelegate(CLLocationManager manager, double desiredAccuracy, bool includeHeading, int timeout, CancellationToken cancelToken) { this.manager = manager; this.tcs = new TaskCompletionSource<Position>(manager); this.desiredAccuracy = desiredAccuracy; this.includeHeading = includeHeading; if (timeout != Timeout.Infinite) { Timer t = null; t = new Timer(s => { if (this.haveLocation) this.tcs.TrySetResult(new Position(this.position)); else this.tcs.TrySetCanceled(); StopListening(); t.Dispose(); }, null, timeout, 0); } cancelToken.Register(() => { StopListening(); this.tcs.TrySetCanceled(); }); }
public static async Task<IMultipartCollection> ReadMultipartAsync(this HttpRequest request, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); request.EnableRewind(); var parts = new MultipartCollection(); using(cancellationToken.Register(request.HttpContext.Abort)) { var contentType = GetContentType(request); var boundary = GetBoundary(contentType); var multipartReader = new MultipartReader(boundary, request.Body); var section = await multipartReader.ReadNextSectionAsync(cancellationToken); while(section != null) { var headers = new HeaderDictionary(section.Headers); var contentDisposition = headers.GetContentDisposition(); await section.Body.DrainAsync(cancellationToken); var part = new Multipart(request.Body, section.BaseStreamOffset.Value, section.Body.Length) { Headers = headers }; parts.Add(part); section = await multipartReader.ReadNextSectionAsync(cancellationToken); } } request.Body.Seek(0, SeekOrigin.Begin); return parts; }
/// <summary> /// Download a file into a stream. /// </summary> /// <param name="path">relative or absolute uri to the file to be downloaded.</param> /// <param name="ct">a cancellation token</param> /// <param name="progress">a progress event callback handler</param> public Task<LiveDownloadOperationResult> DownloadAsync( string path, CancellationToken ct, IProgress<LiveOperationProgress> progress) { LiveUtility.ValidateNotNullOrWhiteSpaceString(path, "path"); var tcs = new TaskCompletionSource<LiveDownloadOperationResult>(); var op = new DownloadOperation( this, this.GetResourceUri(path, ApiMethod.Download), progress, null); op.OperationCompletedCallback = (LiveDownloadOperationResult result) => { if (result.IsCancelled) { tcs.TrySetCanceled(); } else if (result.Error != null) { tcs.TrySetException(result.Error); } else { tcs.TrySetResult(result); } }; ct.Register(op.Cancel); op.Execute(); return tcs.Task; }
public async Task ConnectAsync(string webSocketServerUrl, CancellationToken token) { var uri = default(Uri); if (!Uri.TryCreate(webSocketServerUrl, UriKind.Absolute, out uri)) { throw new ArgumentOutOfRangeException(nameof(webSocketServerUrl), "Expected valid URI argument."); } var retryCount = ConnectRetryCount; while (true) { var timeoutSource = new CancellationTokenSource(ConnectTimeoutMilliseconds); using (token.Register(timeoutSource.Cancel)) { try { await ConnectCoreAsync(uri, timeoutSource.Token).ConfigureAwait(false); return; } catch (OperationCanceledException ex) when (ex.CancellationToken == timeoutSource.Token) { token.ThrowIfCancellationRequested(); } catch { if (--retryCount <= 0) { throw; } } } } }
public void Run(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return; cancellationToken.Register(() => Receiver.CancelMessageWait()); while (true) { if (cancellationToken.IsCancellationRequested) break; string currentMessage = null; try { currentMessage = Receiver.GetNextMessage(); if (cancellationToken.IsCancellationRequested) break; ProcessMessage(currentMessage, cancellationToken); Receiver.AckLastMessage(); } catch (Exception ex) { Log.ErrorFormat(CultureInfo.InvariantCulture, "Worker {0} encountered an error while attempting to process the message \"{1}\".", InstanceId, currentMessage ); Log.Error(ex); Receiver.NackLastMessage(); } } }
public static Task<int> GetIntAsync(CancellationToken token = default(CancellationToken)) { var tcs = new TaskCompletionSource<int>(); if (token.IsCancellationRequested) { tcs.SetCanceled(); return tcs.Task; } var timer = new System.Timers.Timer(3000); timer.AutoReset = false; timer.Elapsed += (s, e) => { tcs.TrySetResult(10); timer.Dispose(); }; if (token.CanBeCanceled) { token.Register(() => { tcs.TrySetCanceled(); timer.Dispose(); }); } timer.Start(); return tcs.Task; }
public static Task AsTask(this System.Threading.CancellationToken token) { TaskCompletionSource taskCompletionSource = new(); token.Register(() => taskCompletionSource.TrySetCanceled(), false); return(taskCompletionSource.Task); }
public async Task<string> WaitForChangeAsync(CancellationToken cancellationToken) { _watchedFiles = GetProjectFilesClosure(_rootProject); foreach (var file in _watchedFiles) { _fileWatcher.WatchDirectory(Path.GetDirectoryName(file)); } var tcs = new TaskCompletionSource<string>(); cancellationToken.Register(() => tcs.TrySetResult(null)); Action<string> callback = path => { // If perf becomes a problem, this could be a good starting point // because it reparses the project on every change // Maybe it could time-buffer the changes in case there are a lot // of files changed at the same time if (IsFileInTheWatchedSet(path)) { tcs.TrySetResult(path); } }; _fileWatcher.OnFileChange += callback; var changedFile = await tcs.Task; _fileWatcher.OnFileChange -= callback; return changedFile; }
public BuildServerClient(CancellationToken token) { m_lock = new object(); m_uris = new List<UriTime>(); token.Register(Stop); Task.Factory.StartNew(Program.FailOnException<object>(Run), token, TaskCreationOptions.LongRunning); }
public static Task SmoothSetAsync(this FrameworkElement @this, DependencyProperty dp, double targetvalue, TimeSpan iDuration, CancellationToken iCancellationToken) { TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); DoubleAnimation anim = new DoubleAnimation(targetvalue, new Duration(iDuration)); PropertyPath p = new PropertyPath("(0)", dp); Storyboard.SetTargetProperty(anim, p); Storyboard sb = new Storyboard(); sb.Children.Add(anim); EventHandler handler = null; handler = delegate { sb.Completed -= handler; sb.Remove(@this); @this.SetValue(dp, targetvalue); tcs.TrySetResult(null); }; sb.Completed += handler; sb.Begin(@this, true); iCancellationToken.Register(() => { double v = (double)@this.GetValue(dp); sb.Stop(); sb.Remove(@this); @this.SetValue(dp, v); tcs.TrySetCanceled(); }); return tcs.Task; }
public static MatchResponse GetDominectMatch(GameCom.GameComClient client, uint width, uint height, string userToken) { var cancellationToken = new System.Threading.CancellationToken(); cancellationToken.Register(() => Console.WriteLine("Request cancelled!")); var mmParam = new MatchmakingParameter(); mmParam.RandomIsDefault = new Nothing(); var request = new MatchRequest() { UserToken = userToken, GameToken = "dom", MatchmakingParameters = mmParam, TimeoutSuggestionSeconds = 400, DomGameParameters = new GameParameter() { BoardWidth = width, BoardHeight = height } }; var reply = client.NewMatch(request, null, DateTime.UtcNow.AddMinutes(1d), cancellationToken); return(reply); }
public static string GetUniqueInstanceName(this Process process, CancellationToken release) { Mutex mutex = null; var instanceId = 0; while (true) { // TODO: Need to distinguish between different instances of a process var mutexName = process.ProcessName + instanceId; bool createdMutex; // Try to create the mutex with ownership try { mutex = new Mutex(true, mutexName, out createdMutex); if (createdMutex) { release.Register(mutex.ReleaseMutex); break; } } catch (UnauthorizedAccessException) { // Mutex exists but we don't have access to it } catch (WaitHandleCannotBeOpenedException) { // Name conflict with another native handle } instanceId++; } return process.ProcessName + " (" + instanceId.ToString() + ")"; }
public NodeDiscoveryService(BitcoinNode node, CancellationToken cancellationToken) { this.node = node; cancellationToken.Register(Signal); this.cancellationToken = cancellationToken; }
public static Task<int> StartProcess (ProcessStartInfo psi, TextWriter stdout, TextWriter stderr, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<int> (); if (cancellationToken.CanBeCanceled && cancellationToken.IsCancellationRequested) { tcs.SetCanceled (); return tcs.Task; } psi.UseShellExecute = false; if (stdout != null) { psi.RedirectStandardOutput = true; } if (stderr != null) { psi.RedirectStandardError = true; } var p = Process.Start (psi); if (cancellationToken.CanBeCanceled) cancellationToken.Register (() => { try { if (!p.HasExited) { p.Kill (); } } catch (InvalidOperationException ex) { if (ex.Message.IndexOf ("already exited") < 0) throw; } }); p.EnableRaisingEvents = true; if (psi.RedirectStandardOutput) { bool stdOutInitialized = false; p.OutputDataReceived += (sender, e) => { try { if (stdOutInitialized) stdout.WriteLine (); stdout.Write (e.Data); stdOutInitialized = true; } catch (Exception ex) { tcs.SetException (ex); } }; p.BeginOutputReadLine (); } if (psi.RedirectStandardError) { bool stdErrInitialized = false; p.ErrorDataReceived += (sender, e) => { try { if (stdErrInitialized) stderr.WriteLine (); stderr.Write (e.Data); stdErrInitialized = true; } catch (Exception ex) { tcs.SetException (ex); } }; p.BeginErrorReadLine (); } p.Exited += (sender, e) => tcs.SetResult (p.ExitCode); return tcs.Task; }
public static CancellationToken ToIterator(this T.CancellationToken ct) { var cts = new CancellationTokenSource(); ct.Register(() => cts.Cancel()); return(cts.Token); }
/// <summary> /// Allows GetResponseAsync call to support cancellation /// </summary> /// <param name="request"></param> /// <param name="ct"></param> /// <returns></returns> public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct) { using (ct.Register(() => request.Abort(), useSynchronizationContext: false)) { try { var response = await request.GetResponseAsync(); ct.ThrowIfCancellationRequested(); return (HttpWebResponse)response; } catch (WebException ex) { // WebException is thrown when request.Abort() is called, // but there may be many other reasons, // propagate the WebException to the caller correctly if (ct.IsCancellationRequested) { // the WebException will be available as Exception.InnerException throw new OperationCanceledException(ex.Message, ex, ct); } // cancellation hasn't been requested, rethrow the original WebException throw; } } }
public static void Run(this IWebHost host, Action<IServiceProvider> action, CancellationToken token, string shutdownMessage) { using (host) { host.Start(); var hostingEnvironment = host.Services.GetService<IHostingEnvironment>(); var applicationLifetime = host.Services.GetService<IApplicationLifetime>(); Console.WriteLine($"Hosting environment: {hostingEnvironment.EnvironmentName}"); Console.WriteLine($"Content root path: {hostingEnvironment.ContentRootPath}"); var serverAddresses = host.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses; if (serverAddresses != null) { foreach (var address in serverAddresses) { Console.WriteLine($"Now listening on: {address}"); } } if (!string.IsNullOrEmpty(shutdownMessage)) { Console.WriteLine(shutdownMessage); } token.Register(state => { ((IApplicationLifetime)state).StopApplication(); }, applicationLifetime); action(host.Services); } }
private async Task Run(string directory, CancellationToken token) { var applicationBase = Environment.CurrentDirectory; var abPrefix = applicationBase.Length + 1; var relBoot = Path.GetDirectoryName(Path.GetFullPath(typeof(Boot).Assembly.Location).Substring(abPrefix)); var relDir = Path.GetFullPath(directory).Substring(abPrefix); if (!token.IsCancellationRequested) { // ReSharper disable AccessToDisposedClosure var isolated = new Isolate<IsolatedRunner, IIsolatedRunner>(null, new AppDomainSetup { ApplicationBase = applicationBase, PrivateBinPath = relDir + Path.PathSeparator + relBoot }); using(isolated) { var reg = token.Register(() => isolated.Value.Cancel());using (reg) try { Debug.WriteLine("Start " + directory); await Task.Factory.StartNew(() => isolated.Value.Run(), token); } catch (TaskCanceledException) { } catch (Exception ex) { _log.Log(2, "Boot Run: " + ex.ToString()); } Debug.WriteLine("Finish " + directory); } // ReSharper restore AccessToDisposedClosure } }
public static Task UploadFromStreamAsync( this CloudBlockBlob blob, Stream stream, CancellationToken ct = default(CancellationToken)) { ICancellableAsyncResult ar = blob.BeginUploadFromStream(stream, null, null); ct.Register(ar.Cancel); return Task.Factory.FromAsync(ar, blob.EndUploadFromStream); }
protected ScheduledAsyncTask(AbstractScheduledEventExecutor executor, PreciseDeadline deadline, TaskCompletionSource promise, CancellationToken cancellationToken) : base(executor, deadline, promise) { _cancellationToken = cancellationToken; _cancellationTokenRegistration = cancellationToken.Register(CancellationAction, this); }
public static Task StartNewDelayed(this TaskFactory factory, int millisecondsDelay, CancellationToken cancellationToken = default(CancellationToken)) { // Validate arguments if (factory == null) throw new ArgumentNullException(nameof(factory)); if (millisecondsDelay < 0) throw new ArgumentOutOfRangeException(nameof(millisecondsDelay)); // Create the timed task var tcs = new TaskCompletionSource<object>(factory.CreationOptions); var ctr = default(CancellationTokenRegistration); // Create the timer but don't start it yet. If we start it now, // it might fire before ctr has been set to the right registration. var timer = new Timer(self => { // Clean up both the cancellation token and the timer, and try to transition to completed ctr.Dispose(); (self as Timer)?.Dispose(); tcs.TrySetResult(null); }, null, -1, -1); // Register with the cancellation token. if (cancellationToken.CanBeCanceled) { // When cancellation occurs, cancel the timer and try to transition to canceled. // There could be a race, but it's benign. ctr = cancellationToken.Register(() => { timer.Dispose(); tcs.TrySetCanceled(); }); } // Start the timer and hand back the task... timer.Change(millisecondsDelay, Timeout.Infinite); return tcs.Task; }
public Task<bool> Sleep(int time, CancellationToken token) { TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); ObjectId id = this.Add(TimeHelper.Now() + time, () => { tcs.SetResult(true); }); token.Register(() => { this.Remove(id); }); return tcs.Task; }
public static async Task <Polyline> DrawPolylineAsync(GeoView view, System.Threading.CancellationToken cancellationToken) { var tcs = new TaskCompletionSource <Polyline>(); PolylineBuilder polylineBuilder = new PolylineBuilder(view.SpatialReference); var sketchlayer = CreateSketchLayer(view); Graphic lineGraphic = new Graphic() { Symbol = DefaultLineSymbol }; Graphic lineMoveGraphic = new Graphic() { Symbol = DefaultLineMoveSymbol }; sketchlayer.Graphics.Add(lineGraphic); sketchlayer.Graphics.Add(lineMoveGraphic); Action cleanupEvents = SetUpHandlers(view, (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(); view.GraphicsOverlays.Remove(sketchlayer); }; cancellationToken.Register(() => tcs.SetCanceled()); Polyline result = null; try { result = await tcs.Task; } finally { cleanup(); } return(result); }
public override Task <ShetabPaymentStep1> BeginPaymentAsync(string paymentcode, decimal amount, string returnUrl, System.Threading.CancellationToken cancellation) { var tcs = new TaskCompletionSource <ShetabPaymentStep1>(); try { var pec = new ir.shaparak.pec.EShopService(); pec.PinPaymentRequestCompleted += new PinPaymentRequestCompletedEventHandler((sender, args) => { if (args.Error != null) { tcs.TrySetException(args.Error); } else if (!args.Cancelled) { try { var result = new ShetabPaymentStep1 <ParsianBankTranStatus>(); result.BankType = this.BankType; result.Code = args.authority; result.SendData.Add("au", args.authority.ToString()); result.Status = args.status; result.Succeeded = (args.status == 0 && args.authority != -1); result.GatewayUrl = Config.GatewayUrl + "?au=" + args.authority.ToString(); result.SendMethod = Config.GatewayMethod; tcs.SetResult(result); } catch (Exception ex) { tcs.TrySetException(ex); } } else { tcs.SetCanceled(); } pec.Dispose(); }); var orderid = SafeClrConvert.ToInt32(paymentcode); var pay = SafeClrConvert.ToInt32(amount); byte pecStatus = 0; long auth = 0; cancellation.Register(() => pec.CancelAsync(paymentcode)); pec.PinPaymentRequestAsync(Config.Credentials.Pin, pay, orderid, returnUrl, auth, pecStatus, paymentcode); } catch (Exception e) { tcs.SetException(e); } return(tcs.Task); }
public static string GetUserToken(GameCom.GameComClient client) { var cancellationToken = new System.Threading.CancellationToken(); cancellationToken.Register(() => Console.WriteLine("Request cancelled!")); var reply = client.GetUserToken(auth, null, null, cancellationToken); return(reply.UserToken); }
public override Task <PaymentProviderBeginPaymentResponse> BeginPaymentAsync(BeginPaymentRequest request, System.Threading.CancellationToken cancellation) { var tcs = new TaskCompletionSource <PaymentProviderBeginPaymentResponse>(); try { var service = new com.zarinpal.www.PaymentGatewayImplementationService(); service.PaymentRequestCompleted += new PaymentRequestCompletedEventHandler((object sender, PaymentRequestCompletedEventArgs args) => { if (args.Error != null) { tcs.TrySetException(args.Error); } else if (!args.Cancelled) { try { var result = new PaymentProviderBeginPaymentResponse <ZarinPalBankTranStatus>(Now); result.ProviderType = this.ProviderType; result.Code = SafeClrConvert.ToLong(args.Authority); result.Status = args.Result; result.Succeeded = (args.Result == 100); result.GatewayUrl = Config.GatewayUrl + $"/{result.Code}"; result.SendMethod = Config.GatewayMethod; result.StrongStatus = args.Result.ToEnum <ZarinPalBankTranStatus>(); tcs.SetResult(result); } catch (Exception ex) { tcs.TrySetException(ex); } } else { tcs.SetCanceled(); } service.Dispose(); }); var amount = SafeClrConvert.ToInt32(request.Amount); cancellation.Register(() => service.CancelAsync(request.PaymentCode)); service.PaymentRequestAsync(Config.Credentials.MerchantId, amount, request.Info, "", "", (string.IsNullOrEmpty(request.ReturnUrl) ? Config.CallbackUrl : request.ReturnUrl)); } catch (Exception e) { tcs.SetException(e); } return(tcs.Task); }
public async System.Threading.Tasks.Task <MessageReceived> ReadTag(System.Threading.CancellationToken cancellationToken, TimeSpan timeout) { if (!IsSupported) { if (_dontThrowExpceptionWhenNotSupported) { return(null); } throw new NotSupportedException("This device does not support NFC (or perhaps it's disabled)"); } _result = new TaskCompletionSource <MessageReceived>(); //needs a message type Task timeoutTask = null; if (timeout != default(TimeSpan)) { timeoutTask = Task.Delay(timeout); } using (cancellationToken.Register((s => ((TaskCompletionSource <MessageReceived>)s).TrySetCanceled()), _result)) { AttachEvents(); StartForegroundMonitoring(); if (timeoutTask != null) { await Task.WhenAny(timeoutTask, _result.Task); if (timeoutTask.IsCompleted) { throw new TimeoutException("NFC message not recieved in time"); } } if (_result.Task.IsCanceled) { StopForegroundDispatch(); DetachEvents(); return(null); } MessageReceived result = await _result.Task; //We don't need to stop the foreground dispatch. Prior to the message been sent the application calls //OnPause which removes the foreground dispatch. By removing the events we prevent it from being added back. //StopForegroundDispatch(); DetachEvents(); return(result); } }
public static async Task <MapPoint> DrawPointAsync(SceneView 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; } catch (TaskCanceledException e) { throw new DrawCanceledExeption("Draw operation was canceled", e, pointGraphic.Geometry); } finally { cleanup(); } return(result); }
public static SetPseudonymResponse.Types.ErrorCode SetPseudonym(GameCom.GameComClient client, string pseudonym) { var cancellationToken = new System.Threading.CancellationToken(); cancellationToken.Register(() => Console.WriteLine("Pseudonym request cancelled!")); var request = new SetPseudonymRequest() { Auth = auth, Pseudonym = pseudonym }; var reply = client.SetGroupPseudonym(request, null, null, cancellationToken); return(reply.ErrorCode); }
/// <summary> /// All providers will ask this server for files and packages, for now the only supported format is tar.gz /// TODO: try if zip compression is also supported /// </summary> /// <returns></returns> private async Task RequestServer(System.Threading.CancellationToken token) { HttpListener listener = new HttpListener(); //this part is tricky: //either run this as administrator or //run: netsh http add urlacl url=http://+:ServerPort/requestID/ user=DOMAIN\username (as an administrator) listener.Prefixes.Add("http://+:" + ServerPort + "/requestID/"); try { var taskCompletionSource = new TaskCompletionSource <HttpListenerContext>(); token.Register(() => { taskCompletionSource.TrySetCanceled();//this will throw }); listener.Start(); while (true) { try { //get the request HttpListenerContext context = await await Task.WhenAny(listener.GetContextAsync(), taskCompletionSource.Task); _ = Task.Run(() => ProcessRequest(context)); // Discard is used so we don't get warnings about not using await... } catch (TaskCanceledException) { //bail out break; } catch (Exception ex) { //TODO: do sth with this exception Console.WriteLine(ex.Message); } } } catch (Exception ex) { Logger.LogError(ex.Message); } finally { listener.Stop(); listener.Close(); } }
/// <summary> /// Actual logic for actually making asynchronous webrequest and retrieving the response for the server. /// </summary> /// <param name="typeArg"></param> /// <param name="httpMethod"></param> /// <param name="resource"></param> /// <returns>A task of RestResponse.</returns> protected virtual Task <RestResponse> GetResponseInternalAsync(Type typeArg) { _isAsyncTimeout = false; HttpWebRequest webRequest = CreateHttpWebRequest(); WriteRequestStream(webRequest); _cancellationTokenSource = new System.Threading.CancellationTokenSource(); System.Threading.CancellationToken cancellationToken = _cancellationTokenSource.Token; Task <WebResponse> result = Task.Factory.FromAsync(webRequest.BeginGetResponse, asyncResult => webRequest.EndGetResponse(asyncResult), (object)webRequest); ThreadPool.RegisterWaitForSingleObject((result as IAsyncResult).AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), webRequest, TimeOut, true); cancellationToken.Register((state) => { webRequest.Abort(); }, webRequest); return(result.ContinueWith((task) => { _cancellationTokenSource.Dispose(); if (task.IsFaulted) { const string message = "An exception has occured, get more detail in inner-exception"; if (_isAsyncTimeout) { return CreateResponse(typeArg, null, new RestException(0, message, null, new Exception("The operation has timed out"))); } else { var aggregateException = task.Exception.Flatten(); var innerExceptionOrAggregateException = aggregateException.InnerExceptions.Count == 1 ? aggregateException.InnerException : aggregateException; return CreateResponse(typeArg, null, new RestException(0, message, null, innerExceptionOrAggregateException)); } } else { return CreateResponse(typeArg, (HttpWebResponse)task.Result, null); } })); }
public async IAsyncEnumerable <ImagePropertyModelView> GetAllImagePropertyAsync(System.Threading.CancellationToken token = default) { bool cancel = false; using var registration = token.Register(() => cancel = true); var listImageProperty = _uow.Query <PropertyImage>().Select(x => new ImagePropertyModelView { IdImageProperty = x.Oid, IdProperty = x.Property.Oid, }).ToListAsync(); foreach (var imagePropertyItem in await listImageProperty) { if (cancel) { break; } yield return(imagePropertyItem); } }
public Task <string> SendAsync(string targetNumber, string message, System.Threading.CancellationToken cancellation) { var tcs = new TaskCompletionSource <string>(); try { var sms = new com.payamak_panel.api.Send(); sms.SendSimpleSMS2Completed += new SendSimpleSMS2CompletedEventHandler((sender, args) => { if (args.Error != null) { tcs.TrySetException(args.Error); } else if (!args.Cancelled) { tcs.SetResult(args.Result); } else { tcs.SetCanceled(); } sms.Dispose(); }); cancellation.Register(() => sms.CancelAsync(_config.Number)); sms.SendSimpleSMS2Async(_config.Username, _config.Password, targetNumber, _config.Number, message, false, _config.Number); } catch (Exception e) { tcs.SetException(e); } return(tcs.Task); }
public static void RegisterGroup(GameCom.GameComClient client) { var cancellationToken = new System.Threading.CancellationToken(); cancellationToken.Register(() => Console.WriteLine("Request cancelled!")); var reply = client.GroupRegistration(new GroupRegistrationRequest() { Auth = auth, MatrNumber = { matrNr } }, null, null, cancellationToken); switch (reply.ErrorCode) { case GroupRegistrationResponse.Types.ErrorCode.Ok: Console.WriteLine("OK:" + reply.ToString()); break; default: Console.WriteLine("Error: " + reply.ErrorCode.ToString()); break; } }
public Task Start(string name, IConnectionManager handler, CancellationToken token, ushort?port, ushort maxConnections) { this._type = name; this._connectionManager = handler; try { IsRunning = true; if (port != null) { throw new NotImplementedException(); } token.Register(this.Stop); } finally { } return(TaskHelper.FromResult(Unit.Default)); }
public static void RegisterMe(GameCom.GameComClient client) { var cancellationToken = new System.Threading.CancellationToken(); cancellationToken.Register(() => Console.WriteLine("Request cancelled!")); var reply = client.UserRegistration(new UserRegistrationRequest() { Fullname = fullname, MatrNumber = matrNr, Email = email, Secret = secret }, null, null, cancellationToken); switch (reply.ErrorCode) { case UserRegistrationResponse.Types.ErrorCode.Ok: Console.WriteLine("OK:" + reply.ToString()); break; default: Console.WriteLine("Error: " + reply.ErrorCode.ToString()); break; } }
/// <summary> /// Reads the data async. /// </summary> /// <returns>The awaitable task.</returns> /// <param name="buffer">The buffer to read into.</param> /// <param name="offset">The offset into the buffer where data is written.</param> /// <param name="count">The number of bytes to read.</param> /// <param name="cancellationToken">Cancellation token.</param> public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { Task <int> rtask; Task rt; if (m_passthrough) { using (var cs = new CancellationTokenSource(m_idletime)) using (cancellationToken.Register(() => cs.Cancel())) { rtask = m_parent.ReadAsync(buffer, offset, count, cs.Token); rt = await Task.WhenAny(m_timeouttask, m_stoptask, rtask); } if (rt != rtask) { if (rt == m_stoptask) { throw new TaskCanceledException(); } else { throw new HttpException(HttpStatusCode.RequestTimeout); } } return(rtask.Result); } if (m_bytesleft <= 0) { return(0); } using (var cs = new CancellationTokenSource(m_idletime)) using (cancellationToken.Register(() => cs.Cancel())) { rtask = m_parent.ReadAsync(buffer, offset, (int)Math.Min(count, m_bytesleft), cs.Token); rt = await Task.WhenAny(m_timeouttask, m_stoptask, rtask); } if (rt != rtask) { if (rt == m_stoptask) { throw new TaskCanceledException(); } else { throw new HttpException(HttpStatusCode.RequestTimeout); } } var r = rtask.Result; if (r == 0) { return(r); } m_bytesleft -= r; m_bytesread += r; return(r); }
public static async Task <Polygon> DrawPolygonAsync(SceneView sceneView, System.Threading.CancellationToken cancellationToken) { var tcs = new TaskCompletionSource <Polygon>(); PolygonBuilder polygonBuilder = new PolygonBuilder(sceneView.SpatialReference); var sketchlayer = CreateSketchLayer(sceneView); Graphic polygonGraphic = new Graphic() { Symbol = DefaultFillSymbol }; Graphic lineMoveGraphic = new Graphic() { Symbol = DefaultLineMoveSymbol }; sketchlayer.Graphics.AddRange(new Graphic[] { polygonGraphic, lineMoveGraphic }); Action cleanupEvents = SetUpHandlers(sceneView, (p) => //On mouse move move completion line around { if (p != null && polygonBuilder.Parts.Count > 0) { lineMoveGraphic.Geometry = new Polyline(new MapPoint[] { polygonBuilder.Parts[0].Last().EndPoint, p, polygonBuilder.Parts[0].First().StartPoint }); } }, (p) => //On tap add a vertex { if (p != null) { polygonBuilder.AddPoint(p); if (polygonBuilder.Parts.Count > 0 && polygonBuilder.Parts[0].Count > 0) { polygonGraphic.Geometry = polygonBuilder.ToGeometry(); lineMoveGraphic.Geometry = null; } } }, (p) => //View tapped - completes task and returns point { tcs.SetResult(polygonBuilder.ToGeometry()); }); Action cleanup = () => { cleanupEvents(); sceneView.GraphicsOverlays.Remove(sketchlayer); }; cancellationToken.Register(() => tcs.SetCanceled()); Polygon result = null; try { result = await tcs.Task; } catch (TaskCanceledException e) { throw new DrawCanceledExeption("Draw operation was canceled", e, polygonBuilder.ToGeometry()); } finally { cleanup(); } return(result); }
/// <summary> /// Reads the data async. /// </summary> /// <returns>The awaitable task.</returns> /// <param name="buffer">The buffer to read into.</param> /// <param name="offset">The offset into the buffer where data is written.</param> /// <param name="count">The number of bytes to read.</param> /// <param name="cancellationToken">Cancellation token.</param> public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { if (m_completed) { return(0); } if (count > m_buf.Length) { Array.Resize(ref m_buf, count + 1024); } Task <int> rtask; Task rt; using (var cs = new CancellationTokenSource(m_idletime)) using (cancellationToken.Register(() => cs.Cancel())) { rtask = m_parent.ReadAsync(m_buf, m_buffersize, Math.Max(m_delimiter.Length - m_buffersize, Math.Min(count, m_buf.Length - m_buffersize)), cs.Token); rt = await Task.WhenAny(m_timeouttask, m_stoptask, rtask); } if (rt != rtask) { if (rt == m_stoptask) { throw new TaskCanceledException(); } else { throw new HttpException(HttpStatusCode.RequestTimeout); } } var r = rtask.Result; m_buffersize += r; if (r == 0) { return(r); } // Return as much as possible var bytes = Math.Min(count, m_buffersize); // Check for the delimiter var ix = FindDelimiterMatch(); // If we found a (partial) delimiter match, // only return bytes leading up to the marker if (ix >= 0) { bytes = Math.Min(count, ix); } // Copy bytes to the reader if (bytes != 0) { Array.Copy(m_buf, 0, buffer, offset, bytes); } // Store what we read ahead in the buffer if (bytes != m_buffersize) { Array.Copy(m_buf, ix, m_buf, 0, m_buffersize - ix); } // Adjust with the bytes taken m_buffersize -= bytes; // If we found the delimiter in full, we are done if (ix > 0 && m_buffersize >= m_delimiter.Length) { m_completed = true; // Drop the delimiter from the buffer m_buffersize -= m_delimiter.Length; // If we have more, stuff it back into the parent's buffer if (m_buffersize != 0) { m_parent.UnreadBytesIntoBuffer(m_buf, m_delimiter.Length, m_buffersize); } m_buffersize = 0; } m_read += bytes; return(bytes); }
public static async Task <Geometry> DrawFreeHandAsync(SceneView sceneView, System.Threading.CancellationToken cancellationToken) { bool isDrawing = false; var tcs = new TaskCompletionSource <Polyline>(); PolylineBuilder polylineBuilder = new PolylineBuilder(sceneView.SpatialReference); var sketchlayer = CreateSketchLayer(sceneView); Graphic lineGraphic = new Graphic() { Symbol = DefaultLineSymbol }; Graphic lineMoveGraphic = new Graphic() { Symbol = DefaultLineMoveSymbol }; sketchlayer.Graphics.AddRange(new Graphic[] { lineGraphic, lineMoveGraphic }); PointerEventHandler onPointerPressed = ((s, e) => { isDrawing = true; sceneView.ManipulationMode = ManipulationModes.None; }); sceneView.PointerPressed += onPointerPressed; PointerEventHandler onPointerMoved = ((s, e) => { if (isDrawing && e != null) { var position = sceneView.ScreenToLocation(e.GetCurrentPoint(sceneView).Position); if (position != null) { polylineBuilder.AddPoint(position); if (polylineBuilder.Parts.Count > 0 && polylineBuilder.Parts[0].Count >= 1) { lineGraphic.Geometry = polylineBuilder.ToGeometry(); } } } }); sceneView.PointerMoved += onPointerMoved; PointerEventHandler onPointerReleased = ((s, e) => { if (isDrawing && polylineBuilder.Parts.Count > 0 && polylineBuilder.Parts[0].Count >= 1) { tcs.SetResult(polylineBuilder.ToGeometry()); } isDrawing = false; }); sceneView.PointerReleased += onPointerReleased; Action cleanup = () => { sceneView.GraphicsOverlays.Remove(sketchlayer); sceneView.ManipulationMode = Windows.UI.Xaml.Input.ManipulationModes.All; sceneView.PointerPressed -= onPointerPressed; sceneView.PointerMoved -= onPointerMoved; sceneView.PointerReleased -= onPointerReleased; }; cancellationToken.Register(() => tcs.SetCanceled()); Polyline result = null; try { result = await tcs.Task; } catch (TaskCanceledException e) { throw new DrawCanceledExeption("Draw operation was canceled", e, polylineBuilder.ToGeometry()); } finally { cleanup(); } return(result); }
public static async Task <string> DownloadUrlAsync(string url, string saveAsDir, Action <int> reportProgressAction = default, Action whenDone = default, System.Threading.CancellationToken cancelToken = default) { // prep file path var fileName = Path.GetFileName(url).Split(new[] { '?' })[0]; Directory.CreateDirectory(saveAsDir); var file = Path.Combine(saveAsDir, fileName); Helper.Logger.Information($"DownloadUrlAsync: downloading {url}"); using (WebClient wc = new WebClient()) { var prog = 0; wc.DownloadProgressChanged += (s, e) => { if (prog == e.ProgressPercentage) { return; } prog = e.ProgressPercentage; reportProgressAction?.Invoke(prog); }; wc.DownloadFileCompleted += (s, e) => whenDone?.Invoke(); try { cancelToken.ThrowIfCancellationRequested(); cancelToken.Register(wc.CancelAsync); var t = wc.DownloadFileTaskAsync(new Uri(url), file); await t; if (t.IsFaulted && t.Exception != null) { throw t.Exception; } Helper.Logger.Information($"DownloadUrlAsync: saved {fileName} to {file}"); } catch (WebException ex) when(ex.Status == WebExceptionStatus.RequestCanceled) { throw new OperationCanceledException(); } catch (AggregateException ex) when(ex.InnerException is WebException exWeb && exWeb.Status == WebExceptionStatus.RequestCanceled) { throw new OperationCanceledException(); } catch (TaskCanceledException) { throw new OperationCanceledException(); } } if (!File.Exists(file)) { var e = new ArgumentException($"Failed to download {fileName}"); Helper.Logger.Error(e, $"DownloadFromUrlAsync: error"); throw e; } var outputDirOrFile = file; // unzip try { if (file.ToLower().EndsWith(".zip")) { outputDirOrFile = Helper.Unzip(file, saveAsDir, true); } } catch (Exception e) { Helper.Logger.Error(e, $"DownloadFromUrlAsync: Unable to unzip file {Path.GetFileName(file)}"); throw new ArgumentException($"Failed to unzip file {Path.GetFileName(file)}.\n -{e.Message}"); } return(outputDirOrFile); }