private void EhLoaded(object sender, RoutedEventArgs e) { this._printerStatusCancellationTokenSource = new System.Threading.CancellationTokenSource(); this._printerStatusCancellationToken = _printerStatusCancellationTokenSource.Token; System.Threading.Tasks.Task.Factory.StartNew(UpdatePrinterStatusGuiElements, _printerStatusCancellationToken); }
public async Task BusinessLoop(CancellationToken token) { try { using (HttpListener listener = new HttpListener()) { listener.Prefixes.Add(Config.HTTPSERVER_LAPTOP_PREFIX); listener.Start(); while (!token.IsCancellationRequested && listener.IsListening) { Task<HttpListenerContext> task = listener.GetContextAsync(); while (!(task.IsCompleted || task.IsCanceled || task.IsFaulted || token.IsCancellationRequested)) { await Task.WhenAny(task, Task.Delay(Config.HTTPSERVER_TIMEOUT_MS)); if (task.Status == TaskStatus.RanToCompletion) { Debug.WriteLine("HTTP Context: Received"); this.ListenerCallback(task.Result); break; } else if (task.Status == TaskStatus.Canceled || task.Status == TaskStatus.Faulted) { Debug.WriteLine("HTTP Context: Errored"); // Error, do nothing } else { Debug.WriteLine("HTTP Context: Timedout/Still waiting"); // Timeout, do nothing } } } } } catch (HttpListenerException e) { // Bail out - this happens on shutdown Debug.WriteLine("HTTP Listener has shutdown: {0}", e.Message); } catch (TaskCanceledException) { Debug.WriteLine("HTTP Task Cancelled"); } catch (Exception e) { Debug.WriteLine("HTTP Unexpected exception: {0}", e.Message); } }
public void Init(Julie owner) { julie = owner; PreferredOutput = new ShellOutput(this); token = new System.Threading.CancellationToken(); //Spin off a thread and listen to an open port listener = new StreamSocketListener(); listener.ConnectionReceived += Listener_ConnectionReceived; Task.Run(new Action(async () => { try { await listener.BindServiceNameAsync("8050"); } catch(Exception er) { Logger.Log(er.Message); } }), token); }
private static void Main(string[] args) { var console = new ClientConsole(); Effort.Provider.EffortProviderConfiguration.RegisterProvider(); var connection = DbConnectionFactory.CreateTransient(); using (var context = new SampleDb(connection, "geo")) { console.WriteLine("Welcome to EF Test Console, type help to check available commands", OutputLevel.Information, null); context.Products.AddRange(new[] { new Product {Name = "CocaCola"}, new Product {Name = "Pepsi"}, new Product {Name = "Starbucks"}, new Product {Name = "Donut"} }); context.SaveChanges(); var ct = new System.Threading.CancellationToken(); Task.Run(() => { SingletonSampleJob.Instance.RunBackgroundWork(ct); }, ct); var command = new RootCommand(console); command.RegisterCommand(new FillOrderCommand(context)); command.RegisterCommand(new EditOrder(context)); command.RegisterCommand(new QueryAuditTrail(context)); command.RegisterCommand(new QueryOrder(context)); command.RegisterCommand(new ToggleController(context)); command.RegisterCommand(new JobController(context)); var commandEngine = new CommandEngine(command); commandEngine.Run(args); } }
async public Task<JsonResult> CaptureQCVM(int id, string ImageName) { VMManager vmm = new VMManager(ConfigurationManager.AppSettings["SubcriptionID"], ConfigurationManager.AppSettings["CertificateThumbprint"]); ApplicationDbContext db = new ApplicationDbContext(); var cloudService = db.QuickCreates.Where(l => l.ID == id).FirstOrDefault(); await vmm.ShutDownVM(cloudService.ServiceName, cloudService.Name); VirtualMachineCaptureVMImageParameters param = new VirtualMachineCaptureVMImageParameters(); param.VMImageLabel = "NewVmImage"; param.VMImageName = "NewVmImage"; param.OSState = "Specialized"; System.Threading.CancellationToken token = new System.Threading.CancellationToken(false); await vmm.CaptureVM(cloudService.ServiceName, cloudService.Name, param.VMImageName); await vmm.RebootVM(cloudService.ServiceName, cloudService.Name); return Json(new { Status = 0 }); }
public override async System.Threading.Tasks.Task PostprocessAsync(System.Data.Common.DbDataReader reader, System.Collections.Generic.IList <System.Exception> exceptions, System.Threading.CancellationToken token) { storeVersion(); await postprocessUpdateAsync(reader, exceptions, token); }
public async Task<Uri> GetDeviceResourceUri(LoadBalancer loadBalancer, CancellationToken cancellationToken) { UriTemplate template = new UriTemplate("loadbalancers/{loadBalancerId}"); Uri baseAddress = await GetBaseUriAsync(cancellationToken); return template.BindByName(baseAddress, new Dictionary<string, string> { { "loadBalancerId", loadBalancer.Id.Value } }); }
/// <summary> /// Asynchronously releases resources owned by this <see cref="Claim"/>. /// </summary> /// <remarks> /// This method calls <see cref="IQueueingService.ReleaseClaimAsync"/> to release messages /// claimed by this claim. To prevent other subscribers from re-claiming the messages, make /// sure to delete the messages before calling <see cref="DisposeAsync"/>. /// </remarks> /// <returns>A <see cref="Task"/> object representing the asynchronous operation.</returns> public Task DisposeAsync(CancellationToken cancellationToken) { lock (_lock) { if (_releaseTask == null) { if (_messages.Length == 0) _releaseTask = InternalTaskExtensions.CompletedTask(); else _releaseTask = _service.ReleaseClaimAsync(_queueName, this, cancellationToken); } } return _releaseTask; }
public void Handshake() { received = 0; source = new System.Threading.CancellationTokenSource(); cancel = source.Token; using (var client = new System.Net.Sockets.TcpClient()) { client.Connect(Environment.MachineName, port); using (var stream = client.GetStream()) { var handshake = Encoding.UTF8.GetBytes("GO"); stream.Write(handshake, 0, handshake.Length); Task.Run(() => ack_nack(stream)); do { int read = stream.Read(buffer, 0, buffer_size); //System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. //at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) if (read == 0) break; var block = Encoding.UTF8.GetString(buffer, 0, read); foreach (var msg in block.Split('\n')) { Console.WriteLine($"Received:[{msg}]"); ++received; } } while (true); source.Cancel(); } } }
/// <summary> /// Gets all existing message queues through a series of asynchronous operations, /// each of which requests a subset of the available queues. /// </summary> /// <remarks> /// Each of the returned tasks is executed asynchronously but sequentially. This /// method will not send concurrent requests to the queueing service. /// <para> /// Due to the way the list end is detected, the final task will return an empty /// collection of <see cref="CloudQueue"/> instances. /// </para> /// </remarks> /// <param name="provider">The queueing service.</param> /// <param name="limit">The maximum number of <see cref="CloudQueue"/> to return from a single task. If this value is <c>null</c>, a provider-specific default is used.</param> /// <param name="detailed"><c>true</c> to return detailed information for each queue; otherwise, <c>false</c>.</param> /// <returns> /// A collections of <see cref="Task{TResult}"/> objects, each of which /// represents an asynchronous operation to gather a subset of the available /// queues. /// </returns> private static IEnumerable<Task<IEnumerable<CloudQueue>>> ListAllQueuesAsync(IQueueingService provider, int? limit, bool detailed, CancellationToken cancellationToken) { if (limit <= 0) throw new ArgumentOutOfRangeException("limit"); CloudQueue lastQueue = null; do { QueueName marker = lastQueue != null ? lastQueue.Name : null; Task<IEnumerable<CloudQueue>> queues = provider.ListQueuesAsync(marker, limit, detailed, cancellationToken); lastQueue = null; yield return queues.ContinueWith(task => { return task.Result.Select(queue => { lastQueue = queue; return queue; }); }); } while (lastQueue != null); }
public async System.Threading.Tasks.Task <EventSourcingTests.Aggregation.when_using_inline_lambdas_to_define_the_projection.SystemState> ResolveAsync(System.Data.Common.DbDataReader reader, System.Threading.CancellationToken token) { EventSourcingTests.Aggregation.when_using_inline_lambdas_to_define_the_projection.SystemState document; document = await _serializer.FromJsonAsync <EventSourcingTests.Aggregation.when_using_inline_lambdas_to_define_the_projection.SystemState>(reader, 0, token).ConfigureAwait(false); return(document); }
public System.Threading.Tasks.Task WaitForConnectionAsync(System.Threading.CancellationToken cancellationToken) { return(default(System.Threading.Tasks.Task)); }
public System.Threading.Tasks.Task ConnectAsync(int timeout, System.Threading.CancellationToken cancellationToken) { return(default(System.Threading.Tasks.Task)); }
public bool Wait(System.TimeSpan timeout, System.Threading.CancellationToken cancellationToken) { throw null; }
public void Wait(System.Threading.CancellationToken cancellationToken) { }
public bool Wait(int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; }
public override async System.Threading.Tasks.Task LoadRowAsync(Npgsql.NpgsqlBinaryImporter writer, EventSourcingTests.Aggregation.when_using_inline_lambdas_to_define_the_projection.SystemState document, Marten.Storage.Tenant tenant, Marten.ISerializer serializer, System.Threading.CancellationToken cancellation) { await writer.WriteAsync(document.GetType().FullName, NpgsqlTypes.NpgsqlDbType.Varchar, cancellation); await writer.WriteAsync(document.Id, NpgsqlTypes.NpgsqlDbType.Uuid, cancellation); await writer.WriteAsync(Marten.Schema.Identity.CombGuidIdGeneration.NewGuid(), NpgsqlTypes.NpgsqlDbType.Uuid, cancellation); await writer.WriteAsync(serializer.ToJson(document), NpgsqlTypes.NpgsqlDbType.Jsonb, cancellation); }
/// <inheritdoc/> public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return base.WriteAsync(buffer, offset, count, cancellationToken) .Select(task => _progress.Report(Position)); }
/// <inheritdoc/> public override Task FlushAsync(CancellationToken cancellationToken) { return base.FlushAsync(cancellationToken) .Select(task => _progress.Report(Position)); }
private async Task <ApiResponse <T> > ExecAsync <T>(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { RestClient client = new RestClient(_baseUrl); client.ClearHandlers(); var existingDeserializer = req.JsonSerializer as IDeserializer; if (existingDeserializer != null) { client.AddHandler("application/json", () => existingDeserializer); client.AddHandler("text/json", () => existingDeserializer); client.AddHandler("text/x-json", () => existingDeserializer); client.AddHandler("text/javascript", () => existingDeserializer); client.AddHandler("*+json", () => existingDeserializer); } else { var customDeserializer = new CustomJsonCodec(configuration); client.AddHandler("application/json", () => customDeserializer); client.AddHandler("text/json", () => customDeserializer); client.AddHandler("text/x-json", () => customDeserializer); client.AddHandler("text/javascript", () => customDeserializer); client.AddHandler("*+json", () => customDeserializer); } var xmlDeserializer = new XmlDeserializer(); client.AddHandler("application/xml", () => xmlDeserializer); client.AddHandler("text/xml", () => xmlDeserializer); client.AddHandler("*+xml", () => xmlDeserializer); client.AddHandler("*", () => xmlDeserializer); client.Timeout = configuration.Timeout; if (configuration.UserAgent != null) { client.UserAgent = configuration.UserAgent; } if (configuration.ClientCertificates != null) { client.ClientCertificates = configuration.ClientCertificates; } InterceptRequest(req); var response = await client.ExecuteAsync <T>(req, cancellationToken); InterceptResponse(req, response); var result = ToApiResponse(response); if (response.ErrorMessage != null) { result.ErrorText = response.ErrorMessage; } if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) { result.Cookies = new List <Cookie>(); } foreach (var restResponseCookie in response.Cookies) { var cookie = new Cookie( restResponseCookie.Name, restResponseCookie.Value, restResponseCookie.Path, restResponseCookie.Domain ) { Comment = restResponseCookie.Comment, CommentUri = restResponseCookie.CommentUri, Discard = restResponseCookie.Discard, Expired = restResponseCookie.Expired, Expires = restResponseCookie.Expires, HttpOnly = restResponseCookie.HttpOnly, Port = restResponseCookie.Port, Secure = restResponseCookie.Secure, Version = restResponseCookie.Version }; result.Cookies.Add(cookie); } } return(result); }
public override System.Threading.Tasks.Task PostprocessAsync(System.Data.Common.DbDataReader reader, System.Collections.Generic.IList <System.Exception> exceptions, System.Threading.CancellationToken token) { storeVersion(); // Nothing return(System.Threading.Tasks.Task.CompletedTask); }
/// <summary> /// Make a HTTP PATCH request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task <ApiResponse <T> > PatchAsync <T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return(ExecAsync <T>(NewRequest(HttpMethod.Patch, path, options, config), config, cancellationToken)); }
/// <summary> /// Refreshes the current claim. /// </summary> /// <remarks> /// This method calls <see cref="IQueueingService.QueryClaimAsync"/> to obtain updated /// information about the current claim, and then synchronously invokes <see cref="RefreshImpl"/> /// to update the current instance to match the results. /// </remarks> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param> /// <returns>A <see cref="Task"/> object representing the asynchronous operation.</returns> public Task RefreshAsync(CancellationToken cancellationToken) { Action<Task<Claim>> applyChanges = task => RefreshImpl(task.Result); return _service.QueryClaimAsync(_queueName, this, cancellationToken).Select(applyChanges); }
public virtual Azure.Data.SchemaRegistry.SchemaRegistrySchema GetSchema(string schemaId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
/// <summary> /// Refreshes the current claim. /// </summary> /// <remarks> /// This method calls <see cref="IQueueingService.QueryClaimAsync"/> to obtain updated /// information about the current claim, and then synchronously invokes <see cref="RefreshImpl"/> /// to update the current instance to match the results. /// </remarks> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param> /// <returns>A <see cref="Task"/> object representing the asynchronous operation.</returns> public Task RefreshAsync(CancellationToken cancellationToken) { Action<Task<Claim>> applyChanges = task => RefreshImpl(task.Result); return _service.QueryClaimAsync(_queueName, this, cancellationToken).ContinueWith(applyChanges, TaskContinuationOptions.ExecuteSynchronously); }
public virtual System.Threading.Tasks.ValueTask <Azure.Data.SchemaRegistry.SchemaRegistrySchema> GetSchemaAsync(string schemaId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
private static IEnumerable<NodeServiceEvent> ListAllNodeServiceEvents(ILoadBalancerService provider, LoadBalancerId loadBalancerId, int? limit, CancellationToken cancellationToken) { if (limit <= 0) throw new ArgumentOutOfRangeException("limit"); NodeServiceEvent lastServiceEvent = null; do { NodeServiceEventId marker = lastServiceEvent != null ? lastServiceEvent.Id : null; IEnumerable<NodeServiceEvent> serviceEvents = provider.ListNodeServiceEventsAsync(loadBalancerId, marker, limit, cancellationToken).Result; lastServiceEvent = null; foreach (NodeServiceEvent serviceEvent in serviceEvents) { yield return serviceEvent; lastServiceEvent = serviceEvent; } } while (lastServiceEvent != null); }
public virtual Azure.Data.SchemaRegistry.SchemaProperties GetSchemaProperties(string groupName, string name, string content, Azure.Data.SchemaRegistry.SerializationType serializationType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
private void PublishMessages(QueueName requestQueueName, QueueName replyQueueName, ref int processedMessages, CancellationToken token) { IQueueingService queueingService = CreateProvider(); processedMessages = 0; Random random = new Random(); while (true) { long x = random.Next(); long y = random.Next(); Message<CalculatorOperation> message = new Message<CalculatorOperation>(TimeSpan.FromMinutes(5), new CalculatorOperation(replyQueueName, "+", x, y)); queueingService.PostMessages(requestQueueName, message); bool handled = false; while (true) { // process reply messages using (Claim claim = queueingService.ClaimMessage(replyQueueName, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1))) { foreach (QueuedMessage queuedMessage in claim.Messages) { CalculatorResult result = queuedMessage.Body.ToObject<CalculatorResult>(); if (result._id == message.Body._id) { // this is the reply to this thread's operation Assert.AreEqual(message.Body._operand1 + message.Body._operand2, result._result); Assert.AreEqual(x + y, result._result); queueingService.DeleteMessage(replyQueueName, queuedMessage.Id, claim); processedMessages++; handled = true; } else if (token.IsCancellationRequested) { // shutdown trigger return; } } } if (handled) break; if (token.IsCancellationRequested) { // shutdown trigger return; } } if (token.IsCancellationRequested) { // shutdown trigger return; } } }
public virtual System.Threading.Tasks.Task <Azure.Response <Azure.Data.SchemaRegistry.SchemaProperties> > RegisterSchemaAsync(string groupName, string name, string content, Azure.Data.SchemaRegistry.SerializationType serializationType, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public Task <int> SaveChangesAsync(System.Threading.CancellationToken cancellationToken) { return(_context.SaveChangesAsync(cancellationToken)); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { // Save request if (request.Content == null) { Request = string.Empty; } else { Request = await request.Content.ReadAsStringAsync(); } RequestHeaders = request.Headers; if (request.Content != null) { ContentHeaders = request.Content.Headers; } Method = request.Method; Uri = request.RequestUri; // Prepare response if (IsPassThrough) { return(await base.SendAsync(request, cancellationToken)); } else { if (_response != null) { return(_response); } else { HttpResponseMessage response = new HttpResponseMessage(StatusCodeToReturn); response.Content = new StringContent(""); return(response); } } }
/// <inheritdoc/> public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return base.ReadAsync(buffer, offset, count, cancellationToken) .Select( task => { _progress.Report(Position); return task.Result; }); }
public static System.Threading.Tasks.Task <Azure.Core.JsonData> FromStreamAsync(System.IO.Stream utf8JsonStream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
/// <inheritdoc/> public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { return base.CopyToAsync(destination, bufferSize, cancellationToken) .Select(task => _progress.Report(Position)); }
protected override Task<Node[]> CreateChildrenAsync(CancellationToken cancellationToken) { return Task.FromResult(RackspaceProductsNode.EmptyChildren); }
/// <summary> /// Converts the cards. If the conversion is successful, advance to CompareCards /// If the conversion fails, show a (hopefully) helpful message and do not advance /// While converting, show an in-progress dialog /// </summary> private void HandleConversionAndShowCompareCardsPage() { var uiScheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext(); var cancellationToken = new System.Threading.CancellationToken(); // Show the dialog that conversion is in progress this.InlineDialog = new InlineDialogVM(new InlineDialogPage_ConvertingCardsVM()); System.Threading.Tasks.Task<Tuple<bool, string>> conversionTask = System.Threading.Tasks.Task<Tuple<bool, string>>.Factory.StartNew(() => { DateTime startConversionTime = DateTime.Now; Tuple<bool, string> result = this.Converter.Convert(); TimeSpan timeSinceStart = DateTime.Now - startConversionTime; // Wait at least this long so the conversion process is convincing double minSeconds = 0.5; if (timeSinceStart.TotalSeconds < minSeconds) { TimeSpan leftover = TimeSpan.FromSeconds(minSeconds - timeSinceStart.TotalSeconds); Console.WriteLine("Finished! Waiting to be convincing for " + leftover); System.Threading.Thread.Sleep(leftover); } return result; }); // Continue with this if conversion completes successfully conversionTask.ContinueWith ( (t) => { if (t.Result.Item1) { this.InlineDialog = null; this.SetCurrentPage(_WizardPage_CompareCards); } else { StringBuilder message = new StringBuilder(); message.AppendLine("An error occurred while trying to convert the deck. Please try again."); message.AppendLine(); message.AppendLine("Details:"); message.AppendLine(t.Result.Item2); this.InlineDialog = new InlineDialogVM(new InlineDialogPage_MessageVM(message.ToString(), "Error While Converting Deck")); } }, cancellationToken, System.Threading.Tasks.TaskContinuationOptions.OnlyOnRanToCompletion, uiScheduler ); // Or continue with this if importing threw an unexpected exception conversionTask.ContinueWith ( (t) => { AggregateException aggEx = t.Exception; StringBuilder message = new StringBuilder(); message.AppendLine("An unexpected Exception occurred while trying to convert the deck. Please try again."); message.AppendLine(); message.AppendLine("Details:"); foreach (Exception e in aggEx.InnerExceptions) { message.AppendLine(e.ToString()); message.AppendLine(); } this.InlineDialog = new InlineDialogVM(new InlineDialogPage_MessageVM(message.ToString(), "Unexpected Exception While Converting Deck")); }, cancellationToken, System.Threading.Tasks.TaskContinuationOptions.OnlyOnFaulted, uiScheduler ); }
private async Task<int> PublishMessages(QueueName requestQueueName, QueueName replyQueueName, CancellationToken token) { IQueueingService queueingService = CreateProvider(); int processedMessages = 0; try { Random random = new Random(); while (true) { long x = random.Next(); long y = random.Next(); Message<CalculatorOperation> message = new Message<CalculatorOperation>(TimeSpan.FromMinutes(5), new CalculatorOperation(replyQueueName, "+", x, y)); await queueingService.PostMessagesAsync(requestQueueName, token, message); bool handled = false; while (true) { // process reply messages using (Claim claim = await queueingService.ClaimMessageAsync(replyQueueName, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), token)) { foreach (QueuedMessage queuedMessage in claim.Messages) { CalculatorResult result = queuedMessage.Body.ToObject<CalculatorResult>(); if (result._id == message.Body._id) { // this is the reply to this thread's operation Assert.AreEqual(message.Body._operand1 + message.Body._operand2, result._result); Assert.AreEqual(x + y, result._result); await queueingService.DeleteMessageAsync(replyQueueName, queuedMessage.Id, claim, token); processedMessages++; handled = true; } else if (token.IsCancellationRequested) { // shutdown trigger return processedMessages; } } // start the dispose process using DisposeAsync so the CancellationToken is honored Task disposeTask = claim.DisposeAsync(token); } if (handled) break; } } } catch (AggregateException ex) { ex.Flatten().Handle( e => { if (e is TaskCanceledException) return true; WebException webException = e as WebException; if (webException != null) { if (webException.Status == WebExceptionStatus.RequestCanceled) return true; } return false; }); return processedMessages; } catch (TaskCanceledException) { return processedMessages; } catch (WebException ex) { if (ex.Status != WebExceptionStatus.RequestCanceled) throw; return processedMessages; } }
public System.Threading.Tasks.Task <long> WriteToAsync(System.IO.Stream stream, System.Threading.CancellationToken cancellationToken) { throw null; }
public async System.Threading.Tasks.Task <EventSourcingTests.Aggregation.when_using_inline_lambdas_to_define_the_projection.SystemState> ResolveAsync(System.Data.Common.DbDataReader reader, System.Threading.CancellationToken token) { var id = await reader.GetFieldValueAsync <System.Guid>(0, token); if (_identityMap.TryGetValue(id, out var existing)) { return(existing); } EventSourcingTests.Aggregation.when_using_inline_lambdas_to_define_the_projection.SystemState document; document = await _serializer.FromJsonAsync <EventSourcingTests.Aggregation.when_using_inline_lambdas_to_define_the_projection.SystemState>(reader, 1, token).ConfigureAwait(false); _session.MarkAsDocumentLoaded(id, document); _identityMap[id] = document; StoreTracker(_session, document); return(document); }
protected override async Task<bool> DeleteNodeAsync(CancellationToken cancellationToken, System.IProgress<int> progress) { await _provider.DeleteQueueAsync(_queue.Name, cancellationToken); return true; }
/// <summary> /// Creates an instance of an HTTP response message based on the information /// provided in the HTTP request message as an operation that will not block. /// </summary> protected override SystemTasks.Task <SystemHttpResponseMessage> SendAsync(SystemHttpRequestMessage request, SystemCancellationToken cancellationToken) => base.SendAsync(HttpRequestMessage.WithRuntimeHeaders(request), cancellationToken);
private async Task<int> SubscribeMessages(QueueName requestQueueName, CancellationToken token) { IQueueingService queueingService = CreateProvider(); int processedMessages = 0; try { while (true) { // process request messages using (Claim claim = await queueingService.ClaimMessageAsync(requestQueueName, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), token)) { List<QueuedMessage> messagesToDelete = new List<QueuedMessage>(); foreach (QueuedMessage queuedMessage in claim.Messages) { CalculatorOperation operation = queuedMessage.Body.ToObject<CalculatorOperation>(); CalculatorResult result; switch (operation._command) { case "+": result = new CalculatorResult(operation, operation._operand1 + operation._operand2); break; case "-": result = new CalculatorResult(operation, operation._operand1 - operation._operand2); break; case "*": result = new CalculatorResult(operation, operation._operand1 * operation._operand2); break; case "/": result = new CalculatorResult(operation, operation._operand1 / operation._operand2); break; default: throw new InvalidOperationException(); } messagesToDelete.Add(queuedMessage); // Assigning result to a local suppresses a warning about calling an asynchronous operation. // In this case, we do not need to wait for the task to finish. Task postTask = queueingService.PostMessagesAsync(operation._replyQueueName, token, new Message<CalculatorResult>(TimeSpan.FromMinutes(5), result)); processedMessages++; } if (messagesToDelete.Count > 0) await queueingService.DeleteMessagesAsync(requestQueueName, messagesToDelete.Select(i => i.Id), token); // start the dispose process using DisposeAsync so the CancellationToken is honored Task disposeTask = claim.DisposeAsync(token); } if (token.IsCancellationRequested) { return processedMessages; } } } catch (AggregateException ex) { ex.Flatten().Handle( e => { if (e is TaskCanceledException) return true; WebException webException = e as WebException; if (webException != null) { if (webException.Status == WebExceptionStatus.RequestCanceled) return true; } return false; }); return processedMessages; } catch (TaskCanceledException) { return processedMessages; } catch (WebException ex) { if (ex.Status != WebExceptionStatus.RequestCanceled) throw; return processedMessages; } }
public virtual Azure.Response PublishCloudEvents(System.Collections.Generic.IEnumerable <Azure.Messaging.EventGrid.Models.CloudEvent> events, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task <Azure.Response> PublishCustomEventsAsync(System.Collections.Generic.IEnumerable <object> events, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task <Azure.Response> PublishEventsAsync(System.Collections.Generic.IEnumerable <Azure.Messaging.EventGrid.Models.EventGridEvent> events, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
/// <summary> /// Renews the claim by resetting the age and updating the TTL for the claim. /// </summary> /// <remarks> /// This method calls <see cref="IQueueingService.UpdateClaimAsync"/> to renew the /// current claim, and then synchronously updates the current instance to reflect /// the new age and time-to-live values. /// </remarks> /// <param name="timeToLive"> /// The new Time-To-Live value for the claim. This value may differ from the original TTL of the claim. /// </param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param> /// <returns>A <see cref="Task"/> object representing the asynchronous operation.</returns> /// <exception cref="ArgumentOutOfRangeException">If <paramref name="timeToLive"/> is negative or <see cref="TimeSpan.Zero"/>.</exception> /// <exception cref="InvalidOperationException">If the claim is empty (i.e. <see cref="Messages"/> is empty).</exception> public Task RenewAsync(TimeSpan timeToLive, CancellationToken cancellationToken) { if (timeToLive <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("timeToLive"); if (_location == null) throw new InvalidOperationException("Empty claims cannot be renewed."); Action<Task> applyChanges = task => { _age = TimeSpan.Zero; TimeToLive = timeToLive; }; return _service.UpdateClaimAsync(_queueName, this, timeToLive, cancellationToken).Select(applyChanges); }
private System.Threading.Tasks.Task PackValueOfStringAsync(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_StringGetOnlyPropertyAndConstructor objectTree, System.Threading.CancellationToken cancellationToken) { return(this._serializer0.PackToAsync(packer, objectTree.String, cancellationToken)); }
internal void Run(System.Threading.CancellationToken cancelToken, bool loop) { // Can only execute one at a time lock (lockObject) { Console.WriteLine("Starting SequenceJob {0}", this.name); this.cancelToken = cancelToken; if (this.setUpAction != null) this.setUpAction.Invoke(); do { if (!this.actions.Any()) WaitUntilCancel(); else { try { foreach (var action in this.actions) action.Invoke(this); } catch (OperationCanceledException) { } } } while (loop && !cancelToken.IsCancellationRequested); if (this.tearDownAction != null) this.tearDownAction.Invoke(); if (cancelToken.IsCancellationRequested) Console.WriteLine("SequenceJob {0} canceled and stopped", this.name); else Console.WriteLine("SequenceJob {0} completed", this.name); } }
protected internal override System.Threading.Tasks.Task PackToAsyncCore(MsgPack.Packer packer, MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_StringGetOnlyPropertyAndConstructor objectTree, System.Threading.CancellationToken cancellationToken) { if ((this.OwnerContext.SerializationMethod == MsgPack.Serialization.SerializationMethod.Array)) { return(MsgPack.Serialization.PackHelpers.PackToArrayAsync(packer, objectTree, this._packOperationListAsync, cancellationToken)); } else { return(MsgPack.Serialization.PackHelpers.PackToMapAsync(packer, objectTree, this._packOperationTableAsync, cancellationToken)); } }
/// <summary> /// Renews the claim by resetting the age and updating the TTL for the claim. /// </summary> /// <remarks> /// This method calls <see cref="IQueueingService.UpdateClaimAsync"/> to renew the /// current claim, and then synchronously updates the current instance to reflect /// the new age and time-to-live values. /// </remarks> /// <param name="timeToLive"> /// The new Time-To-Live value for the claim. This value may differ from the original TTL of the claim. /// </param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param> /// <returns>A <see cref="Task"/> object representing the asynchronous operation.</returns> /// <exception cref="ArgumentOutOfRangeException">If <paramref name="timeToLive"/> is negative or <see cref="TimeSpan.Zero"/>.</exception> /// <exception cref="InvalidOperationException">If the claim is empty (i.e. <see cref="Messages"/> is empty).</exception> public Task RenewAsync(TimeSpan timeToLive, CancellationToken cancellationToken) { if (timeToLive <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("timeToLive"); if (_location == null) throw new InvalidOperationException("Empty claims cannot be renewed."); Action<Task> applyChanges = task => { task.PropagateExceptions(); _age = TimeSpan.Zero; TimeToLive = timeToLive; }; return _service.UpdateClaimAsync(_queueName, this, timeToLive, cancellationToken).ContinueWith(applyChanges, TaskContinuationOptions.ExecuteSynchronously); }
private System.Threading.Tasks.Task UnpackValueOfStringAsync(MsgPack.Unpacker unpacker, UnpackingContext unpackingContext, int indexOfItem, int itemsCount, System.Threading.CancellationToken cancellationToken) { return(MsgPack.Serialization.UnpackHelpers.UnpackReferenceTypeValueAsync(unpacker, unpackingContext, this._serializer0, itemsCount, indexOfItem, typeof(string), "String", MsgPack.Serialization.NilImplication.MemberDefault, this.MsgPack_Serialization_UnpackHelpers_UnpackStringValueAsyncDelegate, this.this_SetUnpackedValueOfStringDelegate, cancellationToken)); }
/// <summary> /// Gets all existing load balancers through a series of asynchronous operations, /// each of which requests a subset of the available load balancers. /// </summary> /// <param name="provider">The load balancer service.</param> /// <param name="limit">The maximum number of <see cref="LoadBalancer"/> objects to return from a single task. If this value is <c>null</c>, a provider-specific default is used.</param> /// <returns> /// A collection of <see cref="LoadBalancer"/> objects describing the available load /// balancers. /// </returns> /// <exception cref="ArgumentNullException">If <paramref name="provider"/> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException">If <paramref name="limit"/> is less than or equal to 0.</exception> private static IEnumerable<LoadBalancer> ListAllLoadBalancers(ILoadBalancerService provider, int? limit, CancellationToken cancellationToken) { if (limit <= 0) throw new ArgumentOutOfRangeException("limit"); LoadBalancer lastLoadBalancer = null; do { LoadBalancerId marker = lastLoadBalancer != null ? lastLoadBalancer.Id : null; IEnumerable<LoadBalancer> loadBalancers = provider.ListLoadBalancersAsync(marker, limit, cancellationToken).Result; lastLoadBalancer = null; foreach (LoadBalancer loadBalancer in loadBalancers) { yield return loadBalancer; lastLoadBalancer = loadBalancer; } // pagination for this call does not match the documentation. } while (false && lastLoadBalancer != null); }
protected internal override System.Threading.Tasks.Task <MsgPack.Serialization.PolymorphicMemberTypeRuntimeType_Normal_StringGetOnlyPropertyAndConstructor> UnpackFromAsyncCore(MsgPack.Unpacker unpacker, System.Threading.CancellationToken cancellationToken) { UnpackingContext unpackingContext = default(UnpackingContext); string ctorArg0 = default(string); ctorArg0 = null; unpackingContext = new UnpackingContext(ctorArg0); if (unpacker.IsArrayHeader) { return(MsgPack.Serialization.UnpackHelpers.UnpackFromArrayAsync(unpacker, unpackingContext, this.this_CreateInstanceFromContextDelegate, this._memberNames, this._unpackOperationListAsync, cancellationToken)); } else { return(MsgPack.Serialization.UnpackHelpers.UnpackFromMapAsync(unpacker, unpackingContext, this.this_CreateInstanceFromContextDelegate, this._unpackOperationTableAsync, cancellationToken)); } }
/// <summary> /// Gets all existing load balancer nodes through a series of asynchronous operations, /// each of which requests a subset of the available nodes. /// </summary> /// <param name="provider">The load balancer service.</param> /// <param name="limit">The maximum number of <see cref="Node"/> to return from a single task. If this value is <c>null</c>, a provider-specific default is used.</param> /// <returns> /// A collection of <see cref="Node"/> objects, each of which represents a subset /// of the available load balancer nodes. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="provider"/> is <c>null</c>. /// <para>-or-</para> /// <para>If <paramref name="loadBalancerId"/> is <c>null</c>.</para> /// </exception> /// <exception cref="ArgumentException">If <paramref name="loadBalancerId"/> is empty.</exception> /// <exception cref="ArgumentOutOfRangeException">If <paramref name="limit"/> is less than or equal to 0.</exception> private static IEnumerable<Node> ListAllLoadBalancerNodes(ILoadBalancerService provider, LoadBalancerId loadBalancerId, int? limit, CancellationToken cancellationToken) { if (provider == null) throw new ArgumentNullException("provider"); if (limit <= 0) throw new ArgumentOutOfRangeException("limit"); // this API call is not currently paginated IEnumerable<Node> loadBalancers = provider.ListNodesAsync(loadBalancerId, cancellationToken).Result; return loadBalancers; }
public System.Threading.Tasks.Task SendMailAsync(System.Net.Mail.MailMessage message, System.Threading.CancellationToken cancellationToken) { throw null; }
public List<Portrait> ProcessFrame(Frame motionFrame, System.Threading.CancellationToken cancellationToken) { _cancellationToken = cancellationToken; var portraits = HandleMotionFrame(motionFrame); return portraits; }
static bool UploadFileWithAzcopyDLL(string filesource, string contentType, string storageAccountName, string storageAccountKey, string containerName, string blobName ) { bool bResult = false; try { System.Net.ServicePointManager.Expect100Continue = false; System.Net.ServicePointManager.DefaultConnectionLimit = Environment.ProcessorCount * 8; Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = new Microsoft.WindowsAzure.Storage.CloudStorageAccount( new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(storageAccountName, storageAccountKey), true); Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer container = blobClient.GetContainerReference(containerName); // Create the container if it doesn't already exist. container.CreateIfNotExists(); Microsoft.WindowsAzure.Storage.Blob.CloudBlob cloudBlob = container.GetBlockBlobReference(blobName); Microsoft.WindowsAzure.Storage.DataMovement.TransferOptions option = new Microsoft.WindowsAzure.Storage.DataMovement.TransferOptions(); //option.ParallelOperations = 64; //option.MaximumCacheSize = 500000000; Microsoft.WindowsAzure.Storage.DataMovement.TransferManager manager = new Microsoft.WindowsAzure.Storage.DataMovement.TransferManager(option); var fileStream = System.IO.File.OpenRead(filesource); Microsoft.WindowsAzure.Storage.DataMovement.TransferLocation source = new Microsoft.WindowsAzure.Storage.DataMovement.TransferLocation(fileStream); Microsoft.WindowsAzure.Storage.DataMovement.TransferLocation destination = new Microsoft.WindowsAzure.Storage.DataMovement.TransferLocation(cloudBlob); //source.SourceUri = new Uri("file://" + sourceFileName); Microsoft.WindowsAzure.Storage.DataMovement.TransferJob job = new Microsoft.WindowsAzure.Storage.DataMovement.TransferJob(source, destination, Microsoft.WindowsAzure.Storage.DataMovement.TransferMethod.SyncCopy); System.Threading.CancellationToken token = new System.Threading.CancellationToken(); //Microsoft.WindowsAzure.Storage.DataMovement.TransferManager.UseV1MD5 = false; job.ContentType = contentType; job.Starting += Job_Starting; job.ProgressUpdated += Job_ProgressUpdated; job.Finished += Job_Finished; Task t = manager.ExecuteJobAsync(job, token); t.Wait(); if (job.IsCompleted == true) bResult = true; } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); if(e.InnerException!= null) Console.WriteLine("Exception: " + e.InnerException.Message); } return bResult; }
private void SubscribeMessages(QueueName requestQueueName, ref int processedMessages, CancellationToken token) { IQueueingService queueingService = CreateProvider(); processedMessages = 0; while (true) { // process request messages using (Claim claim = queueingService.ClaimMessage(requestQueueName, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1))) { List<QueuedMessage> messagesToDelete = new List<QueuedMessage>(); foreach (QueuedMessage queuedMessage in claim.Messages) { if (token.IsCancellationRequested) { return; } CalculatorOperation operation = queuedMessage.Body.ToObject<CalculatorOperation>(); CalculatorResult result; switch (operation._command) { case "+": result = new CalculatorResult(operation, operation._operand1 + operation._operand2); break; case "-": result = new CalculatorResult(operation, operation._operand1 - operation._operand2); break; case "*": result = new CalculatorResult(operation, operation._operand1 * operation._operand2); break; case "/": result = new CalculatorResult(operation, operation._operand1 / operation._operand2); break; default: throw new InvalidOperationException(); } messagesToDelete.Add(queuedMessage); queueingService.PostMessages(operation._replyQueueName, new Message<CalculatorResult>(TimeSpan.FromMinutes(5), result)); processedMessages++; } if (messagesToDelete.Count > 0) queueingService.DeleteMessages(requestQueueName, messagesToDelete.Select(i => i.Id)); } if (token.IsCancellationRequested) { return; } } }
/// <summary> /// Retrieve CSRF protection token /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="operationIndex">Index associated with the operation.</param> /// <param name="cancellationToken">Cancellation Token to cancel the request.</param> /// <returns>Task of ApiResponse (DefaultCrumbIssuer)</returns> public async System.Threading.Tasks.Task <Org.OpenAPITools.Client.ApiResponse <DefaultCrumbIssuer> > GetCrumbWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); string[] _contentTypes = new string[] { }; // to determine the Accept header string[] _accepts = new string[] { "application/json" }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); if (localVarContentType != null) { localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); if (localVarAccept != null) { localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); } localVarRequestOptions.Operation = "BaseApi.GetCrumb"; localVarRequestOptions.OperationIndex = operationIndex; // authentication (jenkins_auth) required // http basic authentication required if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) { localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + Org.OpenAPITools.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); } // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync <DefaultCrumbIssuer>("/crumbIssuer/api/json", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetCrumb", localVarResponse); if (_exception != null) { throw _exception; } } return(localVarResponse); }