private void RunTasks(List <IInitTask> tasks) { foreach (var task in tasks) { if (IsReadyToExecute(task)) { runner.Run(RunTask(task)); } } }
private Task OnCompletedInternal(MediaMoverContext context, bool succeeded, CancellationToken cancelToken) { if (context.AffectedFiles.Any()) { var hasReceived = context.Target == this; if ((!hasReceived && succeeded) || (hasReceived && !succeeded)) { // FS > DB sucessful OR DB > FS failed/aborted: delete all physical files. // Run a background task for the deletion of files (fire & forget) return(_asyncRunner.Run(async(scope, ct, state) => { // Run this fire & forget code in a new scope, because we want // this provider to be disposed as soon as possible. var fileSystem = scope.Resolve <IMediaFileSystem>(); var files = state as string[]; foreach (var file in files) { await fileSystem.TryDeleteFileAsync(file); } }, context.AffectedFiles.ToArray(), cancellationToken: cancelToken)); } } return(Task.CompletedTask); }
public StoreRewardsViewModel(INavigationService navigationService, IAppService appService) : base(navigationService) { _appService = appService; RedemptionPin = "M16602403"; UserInfo = GlobalSettings.User; AsyncRunner.Run(LoadVoucherItems()); }
public StoreViewModel(INavigationService navigationService, IAppService appService, GoogleMapsApiService googleMapsApiService) : base(navigationService) { _appService = appService; _googleMapsApiService = googleMapsApiService; AsyncRunner.Run(Processing()); }
public OrderHistoryViewModel(INavigationService navigationService, IWooCommerceService wooCommerceService) : base(navigationService) { _wooCommerceService = wooCommerceService; AsyncRunner.Run(InitDataAsync()); }
public CouponsViewModel(INavigationService navigationService, IAppService appService, IWooCommerceService wooCommerceService) : base(navigationService) { _appService = appService; _wooCommerceService = wooCommerceService; AsyncRunner.Run(InitDataAsync()); }
public void TestAsyncRunner() { StringBuilder sb = new StringBuilder(); var task = AsyncRunner.Run(() => sb.Append("Done"), default(CancellationToken)); task.Wait(); Assert.AreEqual("Done", sb.ToString()); }
private void OnFacebookPicked(VisualElement sender, TouchEffect.EventArgs.TouchCompletedEventArgs args) { if (_isSocialOpened) { AsyncRunner.Run(_context.OpenFacebookChat()); } OnSocialClicked(null, null); }
public bool RunScheduleTask() { if (ScheduleTask.IsRunning) { Notifier.Information(GetProgressInfo()); return(true); } string scheduleTaskType = ScheduleTaskType; var task = AsyncRunner.Run((container, ct) => { int taskId = 0; try { var svc = container.Resolve <IScheduleTaskService>(); var scheduleTask = svc.GetTaskByType(scheduleTaskType); if (scheduleTask == null) { throw new Exception("Schedule task cannot be loaded"); } taskId = scheduleTask.Id; var job = new Job(scheduleTask); job.Enabled = true; job.Execute(ct, container, false); } catch (Exception) { _scheduleTaskService.EnsureTaskIsNotRunning(taskId); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); task.Wait(100); if (task.IsCompleted) { if (!task.IsFaulted) { Notifier.Success(GetResource("Admin.System.ScheduleTasks.RunNow.Completed")); } else { var exc = task.Exception.Flatten().InnerException; Notifier.Error(exc.Message); Logger.Error(exc.Message, exc); } } else { Notifier.Information(GetResource("Admin.System.ScheduleTasks.RunNow.Progress")); return(true); } return(false); }
/// <summary> /// Initiates the asynchronous execution to get all the remaining results from DynamoDB. /// </summary> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// <returns> /// A Task that can be used to poll or wait for results, or both. /// Results will include the remaining result items from DynamoDB. /// </returns> public Task <List <T> > GetRemainingAsync(CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => { var documents = DocumentSearch.GetRemainingHelper(true); List <T> items = SourceContext.FromDocuments <T>(documents).ToList(); return items; }, cancellationToken)); }
public ActionResult RunJob(int id, string returnUrl = "") { if (!_permissionService.Authorize(StandardPermissionProvider.ManageScheduleTasks)) { return(AccessDeniedView()); } returnUrl = returnUrl.NullEmpty() ?? Request.UrlReferrer.ToString(); var t = AsyncRunner.Run(c => { try { var svc = c.Resolve <IScheduleTaskService>(); var scheduleTask = svc.GetTaskById(id); if (scheduleTask == null) { throw new Exception("Schedule task cannot be loaded"); } var job = new Job(scheduleTask); job.Enabled = true; job.Execute(c, false); } catch { try { _scheduleTaskService.EnsureTaskIsNotRunning(id); } catch (Exception) { } } }); // wait only 100 ms. t.Wait(100); if (t.IsCompleted) { if (!t.IsFaulted) { NotifySuccess(T("Admin.System.ScheduleTasks.RunNow.Completed")); } else { NotifyError(t.Exception.Flatten().InnerException); } } else { NotifyInfo(T("Admin.System.ScheduleTasks.RunNow.Progress")); } return(Redirect(returnUrl)); }
public void Publish <T>(T eventMessage) { if (eventMessage != null) { // Enable event throttling by allowing the very same event to be published only all 150 ms. Timer timer; if (_queue.TryGetValue(eventMessage, out timer)) { // do nothing. The same event was published a tick ago. return; } _queue[eventMessage] = new Timer(RemoveFromQueue, eventMessage, 150, Timeout.Infinite); } var consumerFactory = EngineContext.Current.Resolve <IConsumerFactory <T> >(); if (consumerFactory == null) { return; } IEnumerable <IConsumer <T> > consumers = null; // first fire/forget all async consumers if (consumerFactory.HasAsyncConsumer) { AsyncRunner.Run((c, ct) => { // for wiring up dependencies correctly var newFactory = c.Resolve <IConsumerFactory <T> >(); consumers = newFactory.GetConsumers(true).ToArray(); foreach (var consumer in consumers) { consumer.HandleEvent(eventMessage); } }).ContinueWith(t => { if (t.IsFaulted) { var ex = t.Exception; if (ex != null) { ex.InnerExceptions.Each(x => Logger.Error(x)); } } }); } // now execute all sync consumers consumers = consumerFactory.GetConsumers(false).ToArray(); foreach (var consumer in consumers) { PublishEvent(consumer, eventMessage); } }
public PopupUpdateShippingInfoViewModel(INavigationService navigationService, IWooCommerceService wooCommerceService) : base(navigationService) { _wooCommerceService = wooCommerceService; InitEntryPlaceHolder(); InitErrMessages(); AsyncRunner.Run(InitData()); }
public async Task <JsonResult> Install(InstallModel model) { var t = AsyncRunner.Run( (c, ct, state) => InstallCore(c, (InstallModel)state), model, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); return(Json(await t)); }
public OrdersViewModel(INavigationService navigationService, IAppService appService, IWooCommerceService wooCommerceService) : base(navigationService) { _appService = appService; _wooCommerceService = wooCommerceService; WatchCreateOrderCompleted(); WatchCancelOrder(); AsyncRunner.Run(Processing()); }
public virtual Task InvokeAsync <TMessage>( ConsumerDescriptor descriptor, IConsumer consumer, ConsumeContext <TMessage> envelope, CancellationToken cancelToken = default) where TMessage : class { var d = descriptor; var p = descriptor.WithEnvelope ? (object)envelope : envelope.Message; var fastInvoker = FastInvoker.GetInvoker(d.Method); var ct = cancelToken; Task task; if (d.IsAsync && !d.FireForget) { // The all async case. ct = _asyncRunner.CreateCompositeCancellationToken(cancelToken); task = ((Task)InvokeCore(null, ct)); task.ContinueWith(t => { if (t.IsFaulted) { HandleException(t.Exception, d); } }, TaskContinuationOptions.None); } else if (d.FireForget) { // Sync or Async without await. Needs new dependency scope. task = d.IsAsync ? _asyncRunner.RunTask((scope, ct) => ((Task)InvokeCore(scope, ct))) : _asyncRunner.Run((scope, ct) => InvokeCore(scope, ct)); task.ConfigureAwait(false); } else { // The all sync case try { InvokeCore(null, ct); } catch (Exception ex) { HandleException(ex, d); } task = Task.CompletedTask; } return(task); object InvokeCore(IComponentContext c = null, CancellationToken cancelToken = default)
public async Task <ActionResult> Download(int setId) { var ctx = new LanguageDownloadContext(setId) { AvailableResources = await CheckAvailableResources() }; if (ctx.AvailableResources.Resources.Any()) { var task = AsyncRunner.Run((c, ct, obj) => DownloadCore(c, ct, obj as LanguageDownloadContext), ctx); } return(RedirectToAction("List")); }
public HomeViewModel(INavigationService navigationService, IAppService appService, IWooCommerceService wooCommerceService) : base(navigationService) { _appService = appService; _wooCommerceService = wooCommerceService; NotificationCounts = GlobalSettings.NotificationCounts; NotificationCommand = new Command(NotificationClicked); UserInfo = GlobalSettings.User; FacebookId = GlobalSettings.FacebookPageId; MemberRelated = !GlobalSettings.IsGuest; AsyncRunner.Run(Processing()); }
public async Task <ActionResult> Download(int setId) { if (_services.Permissions.Authorize(StandardPermissionProvider.ManageLanguages)) { var ctx = new LanguageDownloadContext(setId) { AvailableResources = await CheckAvailableResources() }; if (ctx.AvailableResources.Resources.Any()) { var task = AsyncRunner.Run((c, ct, obj) => DownloadCore(c, ct, obj as LanguageDownloadContext), ctx); } } return(RedirectToAction("List")); }
public async Task <ActionResult> Download(int setId) { if (_services.Permissions.Authorize(StandardPermissionProvider.ManageLanguages)) { var ctx = new LanguageDownloadContext(setId); ctx.AvailableResources = await CheckAvailableResources(); if (ctx.AvailableResources.Resources.Any()) { var task = AsyncRunner.Run( (container, ct, obj) => DownloadCore(container, ct, obj as LanguageDownloadContext), ctx, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).ConfigureAwait(false); } } return(RedirectToAction("List")); }
private void Run() { if (_seconds <= 0) { return; } this._startedUtc = DateTime.UtcNow; this._isRunning = true; var jobs = _jobs.Values .Select(job => AsyncRunner.Run((c, ct) => job.Execute(ct, c))) .ToArray(); try { Task.WaitAll(jobs); } catch { } this._isRunning = false; }
public Task ClearCache() { if (!UsesCache()) { return(Task.FromResult <object>(null)); } var cacheUserStore = _userStores.First(); var userStore = _userStores[1]; cacheUserStore.DeleteAllAsync(); var tasks = new List <Task>(); foreach (var user in userStore.Users) { cacheUserStore.CreateAsync(user); tasks.AddRange(AsyncRunner.Run(cacheUserStore.GetServicesAsync(user)).Select(serviceId => cacheUserStore.AddServiceToUserAsync(user, serviceId))); tasks.AddRange(AsyncRunner.Run(cacheUserStore.GetClaimsAsync(user)).Select(claim => cacheUserStore.AddClaimAsync(user, claim))); tasks.AddRange(AsyncRunner.Run(cacheUserStore.GetLoginsAsync(user)).Select(login => cacheUserStore.AddLoginAsync(user, login))); tasks.AddRange(AsyncRunner.Run(cacheUserStore.GetRolesAsync(user)).Select(role => cacheUserStore.AddToRoleAsync(user, role))); } Task.WaitAll(tasks.ToArray()); return(Task.FromResult <object>(null)); }
public void Invoke <TMessage>(ConsumerDescriptor descriptor, IConsumer consumer, ConsumeContext <TMessage> envelope) where TMessage : class { var d = descriptor; var p = descriptor.WithEnvelope ? (object)envelope : envelope.Message; var fastInvoker = FastInvoker.GetInvoker(d.Method); if (!d.FireForget && !d.IsAsync) { // The all synch case try { InvokeCore(); } catch (Exception ex) { HandleException(ex, d); } } else if (!d.FireForget && d.IsAsync) { //// The awaitable Task case //BeginInvoke((Task)InvokeCore(cancelToken: AsyncRunner.AppShutdownCancellationToken), EndInvoke, d); // For now we must go with the AsyncRunner, the above call to BeginInvoke (APM > TPL) does not always // guarantee that the task is awaited and throws exceptions especially when EF is involved. using (var runner = AsyncRunner.Create()) { try { runner.Run((Task)InvokeCore(cancelToken: AsyncRunner.AppShutdownCancellationToken)); } catch (Exception ex) { HandleException(ex, d); } } } else if (d.FireForget && !d.IsAsync) { // A synch method should be executed async (without awaiting) AsyncRunner.Run((c, ct, state) => InvokeCore(c, ct), d) .ContinueWith(t => EndInvoke(t), /*TaskContinuationOptions.OnlyOnFaulted*/ TaskContinuationOptions.None) .ConfigureAwait(false); } else if (d.FireForget && d.IsAsync) { // An async (Task) method should be executed without awaiting AsyncRunner.Run((c, ct) => (Task)InvokeCore(c, ct), d) .ContinueWith(t => EndInvoke(t), TaskContinuationOptions.OnlyOnFaulted) .ConfigureAwait(false); } object InvokeCore(IComponentContext c = null, CancellationToken cancelToken = default(CancellationToken)) { if (d.Parameters.Length == 0) { // Only one method param: the message! return(fastInvoker.Invoke(consumer, p)); } var parameters = new object[d.Parameters.Length + 1]; parameters[0] = p; int i = 0; foreach (var obj in ResolveParameters(c, d, cancelToken).ToArray()) { i++; parameters[i] = obj; } return(fastInvoker.Invoke(consumer, parameters)); } }
/// <summary> /// Initiates the asynchronous execution of the Load operation. /// <seealso cref="Amazon.DynamoDBv2.DataModel.DynamoDBContext.Load"/> /// </summary> /// <typeparam name="T">Type to populate.</typeparam> /// <param name="hashKey">Hash key element of the target item.</param> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// <returns>A Task that can be used to poll or wait for results, or both.</returns> public Task <T> LoadAsync <T>(object hashKey, CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => LoadHelper <T>(hashKey, null, null, true), cancellationToken)); }
/// <summary> /// Initiates the asynchronous execution of the Load operation. /// <seealso cref="Amazon.DynamoDBv2.DataModel.DynamoDBContext.Load"/> /// </summary> /// <typeparam name="T">Type to populate.</typeparam> /// <param name="hashKey">Hash key element of the target item.</param> /// <param name="operationConfig">Overriding configuration.</param> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// <returns>A Task that can be used to poll or wait for results, or both.</returns> public Task <T> LoadAsync <T>(object hashKey, DynamoDBOperationConfig operationConfig, CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => LoadHelper <T>(hashKey, null, operationConfig, true), cancellationToken)); }
/// <summary> /// Initiates the asynchronous execution of the Save operation. /// <seealso cref="Amazon.DynamoDBv2.DataModel.DynamoDBContext.Save"/> /// </summary> /// <typeparam name="T">Type to save as.</typeparam> /// <param name="value">Object to save.</param> /// <param name="operationConfig">Overriding configuration.</param> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// <returns>A Task that can be used to poll or wait for results, or both.</returns> public Task SaveAsync <T>(T value, DynamoDBOperationConfig operationConfig, CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => SaveHelper <T>(value, operationConfig, true), cancellationToken)); }
/// <summary> /// Initiates the asynchronous execution of the Save operation. /// <seealso cref="Amazon.DynamoDBv2.DataModel.DynamoDBContext.Save"/> /// </summary> /// <typeparam name="T">Type to save as.</typeparam> /// <param name="value">Object to save.</param> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// <returns>A Task that can be used to poll or wait for results, or both.</returns> public Task SaveAsync <T>(T value, CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => SaveHelper <T>(value, null, true), cancellationToken)); }
/// <summary> /// Initiates the asynchronous execution of the Delete operation. /// <seealso cref="Amazon.DynamoDBv2.DataModel.DynamoDBContext.Delete"/> /// </summary> /// <typeparam name="T">Type of object.</typeparam> /// <param name="hashKey">Hash key element of the object to delete.</param> /// <param name="rangeKey">Range key element of the object to delete.</param> /// <param name="operationConfig">Config object which can be used to override that table used.</param> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// <returns>A Task that can be used to poll or wait for results, or both.</returns> public Task DeleteAsync <T>(object hashKey, object rangeKey, DynamoDBOperationConfig operationConfig, CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => DeleteHelper <T>(hashKey, rangeKey, operationConfig, true), cancellationToken)); }
/// <summary> /// Initiates the asynchronous execution of the Delete operation. /// <seealso cref="Amazon.DynamoDBv2.DataModel.DynamoDBContext.Delete"/> /// </summary> /// <typeparam name="T">Type of object.</typeparam> /// <param name="hashKey">Hash key element of the object to delete.</param> /// <param name="rangeKey">Range key element of the object to delete.</param> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// <returns>A Task that can be used to poll or wait for results, or both.</returns> public Task DeleteAsync <T>(object hashKey, object rangeKey, CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => DeleteHelper <T>(hashKey, rangeKey, null, true), cancellationToken)); }
/// <summary> /// Initiates the asynchronous execution of the Load operation. /// <seealso cref="Amazon.DynamoDBv2.DataModel.DynamoDBContext.Load"/> /// </summary> /// <typeparam name="T">Type to populate.</typeparam> /// <param name="keyObject">Key of the target item.</param> /// <param name="operationConfig">Overriding configuration.</param> /// <param name="cancellationToken">Token which can be used to cancel the task.</param> /// <returns>A Task that can be used to poll or wait for results, or both.</returns> public Task <T> LoadAsync <T>(T keyObject, DynamoDBOperationConfig operationConfig, CancellationToken cancellationToken = default(CancellationToken)) { return(AsyncRunner.Run(() => LoadHelper <T>(keyObject, operationConfig, true), cancellationToken)); }