public static async Task BlockingReadAsync(this Stream s, byte[] to, int offset, int length, System.Threading.CancellationToken?cancel) { int read = 0; while ((read += await(cancel == null ? s.ReadAsync(to, offset + read, length - read) : s.ReadAsync(to, offset + read, length - read, cancel.Value))) < length) { cancel?.ThrowIfCancellationRequested(); } }
public void LoadAllUnspawnedEntities(System.Threading.CancellationToken token) { IMap map = NitroxServiceLocator.LocateService <IMap>(); int totalEntites = 0; for (int x = 0; x < map.DimensionsInBatches.X; x++) { token.ThrowIfCancellationRequested(); for (int y = 0; y < map.DimensionsInBatches.Y; y++) { for (int z = 0; z < map.DimensionsInBatches.Z; z++) { NitroxInt3 batchId = new NitroxInt3(x, y, z); List <Entity> spawnedEntities = batchEntitySpawner.LoadUnspawnedEntities(batchId, true); lock (entitiesById) { lock (phasingEntitiesByAbsoluteCell) { foreach (Entity entity in spawnedEntities) { if (entity.ParentId != null) { Optional <Entity> opEnt = GetEntityById(entity.ParentId); if (opEnt.HasValue) { entity.Transform.SetParent(opEnt.Value.Transform); } else { Log.Error("Parent not Found! Are you sure it exists? " + entity.ParentId); } } List <Entity> entitiesInCell = GetEntities(entity.AbsoluteEntityCell); entitiesInCell.Add(entity); entitiesById.Add(entity.Id, entity); totalEntites++; } } } Log.Debug($"Loaded {spawnedEntities.Count} entities from batch ({x}, {y}, {z})"); } } if (totalEntites > 0) { Log.Info($"Loading: {(int)((totalEntites/ 504732.0) * 100)}%"); } } }
/// <summary> /// The Set Tier operation sets the tier on a blob. The operation is allowed on a page blob in a premium storage account and on a block blob in a blob storage account (locally redundant storage only). A premium page blob's tier determines the allowed size, IOPS, and bandwidth of the blob. A block blob's tier determines Hot/Cool/Archive storage type. This operation does not update the blob's ETag. /// </summary> /// <param name="clientDiagnostics">The ClientDiagnostics instance used for operation reporting.</param> /// <param name="pipeline">The pipeline used for sending requests.</param> /// <param name="resourceUri">The URL of the service account, container, or blob that is the targe of the desired operation.</param> /// <param name="tier">Indicates the tier to be set on the blob.</param> /// <param name="version">Specifies the version of the operation to use for this request.</param> /// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting-timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a></param> /// <param name="rehydratePriority">Optional: Indicates the priority with which to rehydrate an archived blob.</param> /// <param name="requestId">Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled.</param> /// <param name="leaseId">If specified, the operation only succeeds if the resource's lease is active and matches this ID.</param> /// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param> /// <param name="operationName">Operation name.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Azure.Response</returns> public static async System.Threading.Tasks.ValueTask <Azure.Response> SetAccessTierAsync( Azure.Core.Pipeline.ClientDiagnostics clientDiagnostics, Azure.Core.Pipeline.HttpPipeline pipeline, System.Uri resourceUri, Azure.Storage.Blobs.Models.AccessTier tier, string version, int?timeout = default, Azure.Storage.Blobs.Models.RehydratePriority?rehydratePriority = default, string requestId = default, string leaseId = default, bool async = true, string operationName = "Azure.Storage.Blobs.BlobClient.SetAccessTier", System.Threading.CancellationToken cancellationToken = default) { Azure.Core.Pipeline.DiagnosticScope _scope = clientDiagnostics.CreateScope(operationName); try { _scope.AddAttribute("url", resourceUri); _scope.Start(); using (Azure.Core.HttpMessage _message = SetAccessTierAsync_CreateMessage( pipeline, resourceUri, tier, version, timeout, rehydratePriority, requestId, leaseId)) { if (async) { // Send the request asynchronously if we're being called via an async path await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false); } else { // Send the request synchronously through the API that blocks if we're being called via a sync path // (this is safe because the Task will complete before the user can call Wait) pipeline.Send(_message, cancellationToken); } Azure.Response _response = _message.Response; cancellationToken.ThrowIfCancellationRequested(); return(SetAccessTierAsync_CreateResponse(_response)); } } catch (System.Exception ex) { _scope.Failed(ex); throw; } finally { _scope.Dispose(); } }
public Result Load(string path, System.Threading.CancellationToken ct) { ct.ThrowIfCancellationRequested(); IEnumerable <string> containerPaths = Directory.GetFiles(path, "*.rda"); containerPaths = SortContainerPaths(containerPaths); FileSystem fileSystem = new FileSystem(); foreach (string containerPath in containerPaths) { ct.ThrowIfCancellationRequested(); FileSystem containerFileSystem = this.fileLoader.Load(containerPath, null, ct); fileSystem.OverwriteWith(containerFileSystem, null, ct); } return(new Result(fileSystem, containerPaths)); }
public virtual System.Threading.Tasks.Task SetEmailConfirmedAsync(ModelCodeFluent.Identity.User user, bool confirmed, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); this.ThrowIfDisposed(); if ((user == null)) { throw new System.ArgumentNullException("user"); } user.EmailConfirmed = confirmed; return(System.Threading.Tasks.Task.FromResult(0)); }
public Task <Position> GetPositionAsync(int timeout, System.Threading.CancellationToken cancelToken, bool includeHeading) { var t = GetPositionAsync(timeout, includeHeading); while (t.Status == TaskStatus.Running) { cancelToken.ThrowIfCancellationRequested(); } return(t); }
public virtual System.Threading.Tasks.Task ResetAccessFailedCountAsync(ModelCodeFluent.Identity.User user, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); this.ThrowIfDisposed(); if ((user == null)) { throw new System.ArgumentNullException("user"); } user.AccessFailedCount = 0; return(System.Threading.Tasks.Task.FromResult(user.AccessFailedCount)); }
public virtual System.Threading.Tasks.Task SetLockoutEndDateAsync(ModelCodeFluent.Identity.User user, System.DateTimeOffset lockoutEnd, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); this.ThrowIfDisposed(); if ((user == null)) { throw new System.ArgumentNullException("user"); } user.LockoutEndDateUtc = lockoutEnd.UtcDateTime; return(System.Threading.Tasks.Task.FromResult(0)); }
public virtual System.Threading.Tasks.Task DeleteAsync(ModelCodeFluent.Identity.Role role, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); this.ThrowIfDisposed(); if ((role == null)) { throw new System.ArgumentNullException("role"); } role.Delete(); return(System.Threading.Tasks.Task.FromResult(0)); }
public virtual System.Threading.Tasks.Task SetPhoneNumberAsync(ModelCodeFluent.Identity.User user, string phoneNumber, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); this.ThrowIfDisposed(); if ((user == null)) { throw new System.ArgumentNullException("user"); } user.PhoneNumber = phoneNumber; return(System.Threading.Tasks.Task.FromResult(0)); }
public virtual System.Threading.Tasks.Task UpdateAsync(ModelCodeFluent.Identity.User user, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); this.ThrowIfDisposed(); if ((user == null)) { throw new System.ArgumentNullException("user"); } user.LastProfileUpdateDate = System.DateTime.UtcNow; user.Save(); return(System.Threading.Tasks.Task.FromResult(0)); }
public virtual System.Threading.Tasks.Task SetPasswordHashAsync(ModelCodeFluent.Identity.User user, string passwordHash, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); this.ThrowIfDisposed(); if ((user == null)) { throw new System.ArgumentNullException("user"); } user.Password = passwordHash; user.LastPasswordChangeDate = System.DateTime.UtcNow; return(System.Threading.Tasks.Task.FromResult(0)); }
/// <summary> /// The Batch operation allows multiple API calls to be embedded into a single HTTP request. /// </summary> /// <param name="pipeline">The pipeline used for sending requests.</param> /// <param name="resourceUri">The URL of the service account, container, or blob that is the targe of the desired operation.</param> /// <param name="body">Initial data</param> /// <param name="contentLength">The length of the request.</param> /// <param name="multipartContentType">Required. The value of this header must be multipart/mixed with a batch boundary. Example header value: multipart/mixed; boundary=batch_{GUID}</param> /// <param name="timeout">The timeout parameter is expressed in seconds. For more information, see <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting-timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a></param> /// <param name="requestId">Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled.</param> /// <param name="async">Whether to invoke the operation asynchronously. The default value is true.</param> /// <param name="clientDiagnostics">The ClientDiagnostics instance used for operation reporting.</param> /// <param name="operationName">Operation name.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Azure.Response{Azure.Storage.Blobs.Models.BlobBatchResult}</returns> public static async System.Threading.Tasks.ValueTask <Azure.Response <Azure.Storage.Blobs.Models.BlobBatchResult> > SubmitBatchAsync( Azure.Core.Pipeline.ClientDiagnostics clientDiagnostics, Azure.Core.Pipeline.HttpPipeline pipeline, System.Uri resourceUri, System.IO.Stream body, long contentLength, string multipartContentType, int?timeout = default, string requestId = default, bool async = true, string operationName = "Azure.Storage.Blobs.ServiceClient.SubmitBatch", System.Threading.CancellationToken cancellationToken = default) { Azure.Core.Pipeline.DiagnosticScope _scope = clientDiagnostics.CreateScope(operationName); try { _scope.AddAttribute("url", resourceUri); _scope.Start(); using (Azure.Core.HttpMessage _message = SubmitBatchAsync_CreateMessage( pipeline, resourceUri, body, contentLength, multipartContentType, timeout, requestId)) { if (async) { // Send the request asynchronously if we're being called via an async path await pipeline.SendAsync(_message, cancellationToken).ConfigureAwait(false); } else { // Send the request synchronously through the API that blocks if we're being called via a sync path // (this is safe because the Task will complete before the user can call Wait) pipeline.Send(_message, cancellationToken); } Azure.Response _response = _message.Response; cancellationToken.ThrowIfCancellationRequested(); return(SubmitBatchAsync_CreateResponse(_response)); } } catch (System.Exception ex) { _scope.Failed(ex); throw; } finally { _scope.Dispose(); } }
private static void GenerateAESKeysCancel(System.Threading.CancellationToken ct) { ct.ThrowIfCancellationRequested(); var sw = Stopwatch.StartNew(); var aesM = new AesManaged(); for (int i = 1; i <= NUM_AES_KEYS; i++) { aesM.GenerateKey(); byte[] result = aesM.Key; string hexString = ConvertToHexString(result); // Console.WriteLine("AES KEY: {0} ", hexString); if (sw.Elapsed.TotalSeconds > 0.5) { throw new TimeoutException( "GenerateAESKeysCancel is taking more than 0.5 seconds to complete."); } ct.ThrowIfCancellationRequested(); } Debug.WriteLine("AES: " + sw.Elapsed.ToString()); }
void ProcessMessages(string category, AmazonSQSClient client, string queueName, Action <AmazonSQSClient, Message> processor, System.Threading.CancellationToken token) { token.ThrowIfCancellationRequested(); var queueUrl = client.GetQueueUrlAsync(queueName).GetAwaiter().GetResult().QueueUrl; try { foreach (var message in client.ReceiveMessageAsync(queueUrl).GetAwaiter().GetResult().Messages) { token.ThrowIfCancellationRequested(); Logger.TraceCall("Processor", () => processor(client, message)); Logger.TraceCall("DeleteMessage", () => client.DeleteMessageAsync(queueUrl, message.ReceiptHandle).Wait()); } } catch (AmazonServiceException ex) { Logger.LogWarning(0, $"Amazon service unavailable, returns: {ex.Message}"); } }
internal List <DTO> GetData(System.Threading.CancellationToken token) { var result = new List <DTO>(); for (int i = 0; i < 5; i++) { token.ThrowIfCancellationRequested(); System.Threading.Thread.Sleep(1000); result.Add(new DTO("ID" + i, "name" + i)); } return(result); }
public async Task <Position> GetPositionAsync(System.Threading.CancellationToken cancelToken) { var t = locator.GetGeopositionAsync().AsTask(); while (t.Status == TaskStatus.Running) { cancelToken.ThrowIfCancellationRequested(); } var position = await t; return(position.Coordinate.GetPosition()); }
private static Int32 Sum(System.Threading.CancellationToken cst, Int32 i) { Int32 sum = 0; for (; i > 0; i--) { // if cancel, throw a exception cst.ThrowIfCancellationRequested(); checked { sum += i; } } return(sum); }
public static void CopyDirectory(this string sourceFolder, string destFolder, List <string> blackList, System.Threading.CancellationToken ct) { ct.ThrowIfCancellationRequested(); var dir = new DirectoryInfo(sourceFolder); var destDir = new DirectoryInfo(destFolder); var files = dir.GetFilesExcept(blackList).ToList(); if (!destDir.Exists && files.Count != 0) { destDir.Create(); } foreach (FileInfo file in files) { ct.ThrowIfCancellationRequested(); file.CopyTo(Path.Combine(destFolder, file.Name), true); } foreach (DirectoryInfo subDir in dir.GetDirectoriesExcept(blackList)) { CopyDirectory(subDir.FullName, Path.Combine(destFolder, subDir.Name), blackList, ct); } }
/// <summary> /// Implement all the query logic in this method. /// </summary> /// <remarks> /// The cancellationToken must be checked when it is safe to cancel the /// operation. The blocking logic between two check points for cancellationToken /// should run as quick as possible. The logic will still be aborted if it takes too /// long after cancellationToken is canceled but no cancellation work is actually performed. /// The cancellation work can be simply return from the method or throw an OperationCanceledException. /// </remarks> /// <param name="cancellationToken">The cancellationToken to be checked.</param> /// <returns>Queried result</returns> protected override TaskQuickStatus QueryStatus(System.Threading.CancellationToken cancellationToken) { int count; for (count = 0; count < COUNT; count++) { // Check cancellationToken for the canceled state. cancellationToken.ThrowIfCancellationRequested(); // TODO: do real work, keep it as quick as possible. // Here, simply uses a timed wait to make it look like working on something. cancellationToken.WaitHandle.WaitOne(WAIT_TIMEOUT); } // Check the cancellationToken again cancellationToken.ThrowIfCancellationRequested(); return(new TaskQuickStatus() { Mark = count.ToString(CultureInfo.CurrentCulture), StatusTips = String.Empty }); }
private void StartFinding(System.Threading.CancellationToken ct) { int count = MQ.Count; CountOfTasks = count; CountOfCompletedTasks = 0; for (int i = 0; i < count; i++) { int currentTaskNumber = i; Task.Run(() => { try { var result = MQ[currentTaskNumber].Where((item) => (Predicate(item))); foreach (var entry in result) { ct.ThrowIfCancellationRequested(); if (entry.Type == EntryType.File) { fileList.Add((MyFile)entry); } else if (entry.Type == EntryType.Folder) { dirList.Add((MyFolder)entry); } NewElementHandler(entry); } } catch (OperationCanceledException) { } catch (Exception exc) { System.Windows.Forms.MessageBox.Show(exc.Message); } finally { lock (CompeledTasksIncSyncRoot) { CountOfCompletedTasks++; if (CountOfCompletedTasks == CountOfTasks) { SearchingCompletedHandler(); } } } }); } }
public static async Task RunAsync(this System.Threading.SemaphoreSlim semaphore, Func <Task> action, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); await action().ConfigureAwait(false); } finally { semaphore.Release(); } }
internal void Start(System.Threading.CancellationToken token) { while (true) { token.ThrowIfCancellationRequested(); if (DateTime.Now.Hour == this.HOUR_RUN && NextRun < DateTime.Now) { Run(token); } else { log.InfoFormat("Wait {0} h last {1} Minute", HOUR_RUN, (int)(DateTime.Now - NextRun).TotalMinutes); token.WaitHandle.WaitOne(60000); } } }
/// <summary> /// /// </summary> /// <typeparam name="T">Type of IEnumerable items</typeparam> /// <param name="action">The action to perform on each element.</param> /// <param name="cancellationToken">A <see cref="T:System.Threading.CancellationToken" /> to observe while waiting for the task to complete.</param> /// <returns></returns> public static async Task EachAsync <T>(this IEnumerable <T> items, Func <T, Task> action, System.Threading.CancellationToken cancellationToken) { IEnumerator <T> enumerator = items.GetEnumerator(); if (enumerator.MoveNext()) { bool task; do { cancellationToken.ThrowIfCancellationRequested(); T current = enumerator.Current; task = enumerator.MoveNext(); await action(current).ConfigureAwait(false); }while (task); } }
public virtual System.Threading.Tasks.Task <System.Collections.Generic.IList <string> > GetRolesAsync(ModelCodeFluent.Identity.User user, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); this.ThrowIfDisposed(); if ((user == null)) { throw new System.ArgumentNullException("user"); } System.Collections.Generic.IList <string> roleNames = new System.Collections.Generic.List <string>(); for (System.Collections.Generic.IEnumerator <ModelCodeFluent.Identity.Role> enumerator = user.Roles.GetEnumerator(); enumerator.MoveNext(); ) { roleNames.Add(enumerator.Current.Name); } return(System.Threading.Tasks.Task.FromResult(roleNames)); }
private static double CalculateStandardDeviation( System.Threading.CancellationToken ct, double mean) { ct.ThrowIfCancellationRequested(); return(inputIntegers.AsParallel().WithCancellation(ct).Aggregate( // Seed 0d, // Update accumulator function (subTotal, thisNumber) => subTotal + Math.Pow((thisNumber - mean), 2), // Combine accumulators function (total, thisTask) => total + thisTask, // Result selector (finalSum) => Math.Sqrt((finalSum / (inputIntegers.Count() - 1))))); }
public static async Task DownloadFileAsync(string url, string fileName, IProgress <double> progress, System.Threading.CancellationToken token) { if (File.Exists(fileName)) { File.Delete(fileName); } using (var client = new HttpClient()) { var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); if (!response.IsSuccessStatusCode) { throw new Exception($"The request returned with HTTP status code {response.StatusCode}"); } var total = response.Content.Headers.ContentLength ?? -1L; var canReportProgress = total != -1 && progress != null; using (var sFile = new FileStream(fileName, FileMode.CreateNew)) using (var stream = await response.Content.ReadAsStreamAsync()) { var totalRead = 0L; var buffer = new byte[4096]; var isMoreToRead = true; do { token.ThrowIfCancellationRequested(); var read = await stream.ReadAsync(buffer, 0, buffer.Length, token); if (read == 0) { isMoreToRead = false; } else { var data = new byte[read]; buffer.ToList().CopyTo(0, data, 0, read); await sFile.WriteAsync(data, 0, data.Length, token); totalRead += read; if (canReportProgress) { progress.Report(totalRead * 1d / (total * 1d) * 100); } } } while (isMoreToRead); } } }
/// <param name="quality"> if 100 save texture to png, else to jpg with selected quality</param> public async void Init() { var cardsId = new List <string>(); for (int i = 0; i < 10; i++) { try { var texture = await _webService.LoadTexture("https://picsum.photos", 180, 180, _token); _token.ThrowIfCancellationRequested(); int quality = 100; var img = quality == 100 ? texture.EncodeToPNG() : texture.EncodeToJPG(quality); var extension = quality == 100 ? "png" : "jpg"; cardsId.Add(texture.name); var filename = $"{_pathToCardsArt}/{texture.name}.{extension}"; using (var fs = File.Open(filename, FileMode.Create)) { await fs.WriteAsync(img, 0, img.Length, _token); } await Task.Delay(300, _token); // limit the number of requests per second } catch (OperationCanceledException e) { Debug.Log("Resource download has been canceled"); } } #if UNITY_EDITOR AssetDatabase.Refresh(); // freezy Editor #endif foreach (var id in cardsId) { #if UNITY_EDITOR var asset = _cacheService.Load <Sprite>($"CardsArt/{id}"); #else // todo Load From persistentDataPath #endif } Initilized.Value = true; }
public virtual System.Threading.Tasks.Task <System.Collections.Generic.IList <System.Security.Claims.Claim> > GetClaimsAsync(ModelCodeFluent.Identity.User user, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); this.ThrowIfDisposed(); if ((user == null)) { throw new System.ArgumentNullException("user"); } System.Collections.Generic.IList <System.Security.Claims.Claim> result = new System.Collections.Generic.List <System.Security.Claims.Claim>(); for (System.Collections.Generic.IEnumerator <ModelCodeFluent.Identity.UserClaim> enumerator = user.Claims.GetEnumerator(); enumerator.MoveNext(); ) { ModelCodeFluent.Identity.UserClaim userClaim = enumerator.Current; result.Add(new System.Security.Claims.Claim(userClaim.Type, userClaim.Value, userClaim.ValueType, userClaim.Issuer, userClaim.OriginalIssuer)); } return(System.Threading.Tasks.Task.FromResult(result)); }
public virtual System.Threading.Tasks.Task <System.Collections.Generic.IList <Microsoft.AspNet.Identity.UserLoginInfo> > GetLoginsAsync(ModelCodeFluent.Identity.User user, System.Threading.CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); this.ThrowIfDisposed(); if ((user == null)) { throw new System.ArgumentNullException("user"); } System.Collections.Generic.IList <Microsoft.AspNet.Identity.UserLoginInfo> result = new System.Collections.Generic.List <Microsoft.AspNet.Identity.UserLoginInfo>(); for (System.Collections.Generic.IEnumerator <ModelCodeFluent.Identity.UserLogin> enumerator = user.Logins.GetEnumerator(); enumerator.MoveNext(); ) { ModelCodeFluent.Identity.UserLogin userLogin = enumerator.Current; result.Add(new Microsoft.AspNet.Identity.UserLoginInfo(userLogin.ProviderName, userLogin.ProviderKey)); } return(System.Threading.Tasks.Task.FromResult(result)); }