public void tears_down_context_after_executing() { var task = new BackgroundTask(() => true); task.Start(null); Assert.That(BackgroundTask.CurrentContext, Is.Null); }
public void Add(BackgroundTask task) { task.Finished += TaskFinished; lock (synclock) tasks.Push(task); }
public MainWindow() { InitializeComponent(); Instance = this; Model = MainWindowModel.Create(); DataContext = Model; backgroundTask = new BackgroundTask(() => { bool b = Task.Run(async () => { GoSettings goSettings = new GoSettings(); logger.Info("Setting up..."); goSettings.AuthType = AuthType.Ptc; await txtUsername.SafeAccessAsync((t) => goSettings.PtcUsername = t.Text); await txtPassword.SafeAccessAsync((t) => goSettings.PtcPassword = t.Password); await dudLatitude.SafeAccessAsync((d) => goSettings.DefaultLatitude = d.Value ?? 0); await dudLongitude.SafeAccessAsync((d) => goSettings.DefaultLongitude = d.Value ?? 0); try { logger.Info("Beginning to farm..."); PokemonGo.RocketAPI.Logger.SetLogger(new NLogLogger()); await new GoLogic(goSettings).Execute(); } catch (Exception e) { if (e is PtcOfflineException) { logger.Info("Could not log in (login servers may be down or invalid credentials)"); } else { logger.Error(e); } } return true; }).Result; }); SetupUI(); }
public void sets_up_context_when_executing_queued_work() { var task = new BackgroundTask( () =>{ Assert.That(BackgroundTask.CurrentContext, Is.Not.Null); return true; }); task.Start(null); }
public void is_busy_during_work() { BackgroundTask task = null; task = new BackgroundTask( () => { Assert.That(task.IsBusy, Is.True); return true; }); task.Start(null); }
public void can_queue_work() { bool wasExecuted = false; var handle = new ManualResetEvent(false); var task = new BackgroundTask(() =>{ wasExecuted = true; handle.Set(); return null; }); task.Start(null); handle.WaitOne(1000); Assert.That(wasExecuted, Is.True); }
public static void ExecuteTask(BackgroundTask task) { //for (var i = 0; i < 10; i++) //{ using (var session = DocumentStore.OpenSession()) { switch (task.Run(session, _documentStore, DropboxHelper)) { case true: case false: return; case null: break; } } //} }
protected virtual void Dispose(bool disposing) { if (Interlocked.Read(ref _disposed) == 0) { Interlocked.Exchange(ref _disposed, 1); if (TextBuffer != null) { TextBuffer.Changed -= OnTextBufferChanged; TextBuffer = null; } if (BackgroundTask != null) { BackgroundTask.Dispose(); BackgroundTask = null; } } }
public override void Begin() { _task = new BackgroundTask( delegate(IBackgroundTaskContext context) { try { var results = _owner.GetShortList(_query); context.Complete(results); } catch (Exception e) { context.Error(e); } }, false, _query); _task.Terminated += OnTerminated; _task.Run(); }
public async Task<int> CreateTask(TaskType type, byte[] data = null, object config = null) { var task = new BackgroundTask { Type = type, Status = BackgroundTaskStatus.New, Config = config?.SerializeToXml(), Created = DateTime.Now, Data = data }; TaskRepository.Add(task); TaskRepository.SaveChanges(); return task.Id; }
internal static void Initialize() { lock (s_init_lock) { if (s_initialized) { return; } TrinityConfig.EnsureConfig(); LoggingConfig.Instance.LogEchoOnConsole = LoggingConfig.Instance.LogEchoOnConsole; //force sync the lazy value CLogInitialize(); s_bgtask = new BackgroundTask(CollectLogEntries, c_LogEntryCollectorIdleInterval); BackgroundThread.AddBackgroundTask(s_bgtask); s_initialized = true; s_logtofile = LoggingConfig.Instance.LogToFile; SetLogDirectory(LoggingConfig.Instance.LogDirectory); } }
public void Initialize(DbContext ezDbContext) { EzCMSEntities dbContext = ezDbContext as EzCMSEntities; if (dbContext != null) { var backgroundTask = new BackgroundTask { Name = GetName(), Description = GetName(), Status = BackgroundTaskEnums.TaskStatus.Active, ScheduleType = BackgroundTaskEnums.ScheduleType.Interval, Interval = 60 }; dbContext.BackgroundTasks.AddIfNotExist(t => t.Name, backgroundTask); } }
/// <summary> /// Executes code on the background thread. /// </summary> /// <param name="backgroundAction">The background action.</param> /// <param name="uiCallback">The UI callback.</param> /// <param name="progressChanged">The progress change callback.</param> public IBackgroundTask ExecuteOnBackgroundThread(Action backgroundAction, RunWorkerCompletedEventHandler uiCallback, ProgressChangedEventHandler progressChanged) { var task = new BackgroundTask( () =>{ backgroundAction(); return null; }); if(uiCallback != null) task.Completed += (s, e) => ExecuteOnUIThread(() => uiCallback(s, e)); if(progressChanged != null) task.ProgressChanged += (s, e) => ExecuteOnUIThread(() => progressChanged(s, e)); task.Start(null); return task; }
private async Task InsertBackgroundTaskAsync(BackgroundTask task, IDbConnection db, IDbTransaction t) { var sql = $@" INSERT INTO {TaskTable} (Priority, Attempts, Handler, RunAt, MaximumRuntime, MaximumAttempts, DeleteOnSuccess, DeleteOnFailure, DeleteOnError, Expression, Start, [End], ContinueOnSuccess, ContinueOnFailure, ContinueOnError) VALUES (:Priority, :Attempts, :Handler, :RunAt, :MaximumRuntime, :MaximumAttempts, :DeleteOnSuccess, :DeleteOnFailure, :DeleteOnError, :Expression, :Start, :End, :ContinueOnSuccess, :ContinueOnFailure, :ContinueOnError); SELECT MAX(Id) FROM {TaskTable}; "; task.Id = (await db.QueryAsync <int>(sql, task, t)).Single(); var createdAtString = await db.QuerySingleAsync <string>($"SELECT \"CreatedAt\" FROM {TaskTable} WHERE \"Id\" = :Id", new { task.Id }, t); task.CreatedAt = DateTimeOffset.Parse(createdAtString); }
public List <BackgroundTask> GetTasks() { try { var bgTasks = new List <BackgroundTask>(); foreach (var task in _tasks) { var bgTask = new BackgroundTask(); bgTask.Id = task.Id; bgTask.Type = task.Type; bgTask.Description = task.Description; bgTask.Description1 = task.Description1; bgTask.Remark = task.Remark; bgTask.Status = (int)task.Status; var statusName = EnumHelper.GetNameById <TaskStatus>(bgTask.Status); var statusDspName = ""; if (!statusName.IsNullOrEmpty()) { statusDspName = WinformRes.ResourceManager.GetString("BackgroundTaskStatus_" + statusName); if (statusDspName.IsNullOrEmpty()) { statusDspName = statusName; } } else { statusDspName = WinformRes.Unknown; } bgTask.StatusName = statusDspName; bgTask.JoinTime = task.JoinTime; bgTask.StartTime = task.StartTime; bgTask.CompleteTime = task.CompleteTime; bgTasks.Add(bgTask); } return(bgTasks); } catch (Exception ex) { throw new ArgumentException("\n>> " + GetType().FullName + ".GetTasks Error: " + ex.Message); } }
private void SendServiceStatusChangedNotification() { // send an e-mail notification try { BackgroundTask topTask = TaskManager.TopTask; bool sendNotification = Utils.ParseBool(topTask.GetParamValue(SystemTaskParams.PARAM_SEND_EMAIL), false); // Ensure notification is required if (!sendNotification) { TaskManager.Write("Notification send is not required, thus skipped"); return; } Service service = (Service)topTask.GetParamValue(SystemTaskParams.PARAM_SERVICE); int smtpResult = 0; switch (service.Status) { case ServiceStatus.Active: smtpResult = MiscController.SendServiceActivatedNotification(service.ServiceId); break; case ServiceStatus.Suspended: smtpResult = MiscController.SendServiceSuspendedNotification(service.ServiceId); break; case ServiceStatus.Cancelled: smtpResult = MiscController.SendServiceCanceledNotification(service.ServiceId); break; } // if (smtpResult != 0) { TaskManager.WriteWarning("Unable to send e-mail notification"); TaskManager.WriteParameter("SMTP Status", smtpResult); } } catch (Exception ex) { TaskManager.WriteError(ex); } }
/// <summary> /// Executes code on the background thread. /// </summary> /// <param name="backgroundAction">The background action.</param> /// <param name="uiCallback">The UI callback.</param> /// <param name="progressChanged">The progress change callback.</param> public IBackgroundTask ExecuteOnBackgroundThread(Action backgroundAction, Action<BackgroundTaskCompletedEventArgs> uiCallback, Action<BackgroundTaskProgressChangedEventArgs> progressChanged) { var task = new BackgroundTask( _threadPool, () =>{ backgroundAction(); return null; }); if (uiCallback != null) task.Completed += (s, e) => ExecuteOnUIThread(() => uiCallback(e)); if (progressChanged != null) task.ProgressChanged += (s, e) => ExecuteOnUIThread(() => progressChanged(e)); task.Enqueue(null); return task; }
/// <summary> /// Called by the framework just before the <see cref="ProgressGraphic"/> is rendered. /// </summary> public override void OnDrawing() { if (_synchronizationContext == null) { _synchronizationContext = SynchronizationContext.Current; } if (_progressProvider != null) { float progress; string message; if (_progressProvider.IsRunning(out progress, out message)) { if (_updateTask == null && _synchronizationContext != null) { _updateTask = new BackgroundTask(UpdateProgressBar, true, null); _updateTask.Terminated += OnTaskTerminated; _updateTask.Run(); } } else { _progressProvider = null; if (_updateTask != null) { _updateTask.RequestCancel(); _updateTask = null; } if (_autoClose && _synchronizationContext != null) { _synchronizationContext.Post(s => Close(), null); } } _graphics.Progress = progress; _graphics.Text = message; } base.OnDrawing(); }
public Task <bool> SaveAsync(BackgroundTask task) { var db = GetDbConnection(); var t = BeginTransaction((SqlConnection)db, out var owner); var success = false; try { if (task.Id == default) { InsertBackgroundTask(task, db, t); } else { UpdateBackgroundTask(task, db, t); } UpdateTagMapping(task, db, t); success = true; } catch (Exception e) { _logger.Error(() => "Error saving task with ID {Id}", e, task.Id); } finally { if (owner) { if (success) { CommitTransaction(t); } else { RollbackTransaction(t); } } } return(Task.FromResult(success)); }
public void Initialize(DbContext ezDbContext) { EzCMSEntities dbContext = ezDbContext as EzCMSEntities; if (dbContext != null) { var backgroundTask = new BackgroundTask { Name = GetName(), Description = GetName(), Status = BackgroundTaskEnums.TaskStatus.Disabled, ScheduleType = BackgroundTaskEnums.ScheduleType.Daily, // 1 AM UTC StartTime = new TimeSpan(1, 0, 0) }; dbContext.BackgroundTasks.AddIfNotExist(t => t.Name, backgroundTask); } }
/// <summary> /// Processes the specified work item. /// </summary> /// <param name="backgroundTask">The work item.</param> public void Process(BackgroundTask backgroundTask) { if (backgroundTask == null) { Debug.Fail("Not allowed to be null"); return; } Trace.WriteLine("Signaling processing thread to process the queued task"); queuedBackgroundTask = backgroundTask; OnPropertyChanged("QueuedBackgroundTask"); ToggleStatus(false); // Signal our processing thread to process the queued task signal.Set(); }
protected void SendAddPackageWithResourcesNotification() { try { BackgroundTask topTask = TaskManager.TopTask; bool sendLetter = Utils.ParseBool(topTask.GetParamValue("SendLetter"), false); if (sendLetter) { int sendResult = PackageController.SendPackageSummaryLetter(topTask.ItemId, null, null, true); CheckSmtpResult(sendResult); } } catch (Exception ex) { TaskManager.WriteWarning(ex.StackTrace); } }
/// <summary> /// Constructor. /// </summary> /// <param name="task">The task that will run in the background, reporting its progress to the foreground UI thread.</param> /// <param name="autoClose">Whether or not the progress dialog should close automatically upon task completion.</param> /// <param name="progressBarStyle">The style of the progress bar.</param> /// <param name="startProgressMessage"></param> public ProgressDialogComponent(BackgroundTask task, bool autoClose, ProgressBarStyle progressBarStyle, string startProgressMessage = null) { _task = task; _autoClose = autoClose; _progressBar = 0; _progressMessage = startProgressMessage ?? String.Empty; _progressBarStyle = progressBarStyle; _marqueeSpeed = 100; if (_task != null) { _enableCancel = _task.SupportsCancel; } else { _enableCancel = false; } }
public override bool BuildRegions(OutlineRegionCollection newRegions) { lock (_threadLock) { if (IsDisposed || !EditorTree.IsReady) { return(false); } AstRoot rootNode = null; try { rootNode = EditorTree.AcquireReadLock(_treeUserId); if (rootNode != null) { OutliningContext context = new OutliningContext(); context.Regions = newRegions; rootNode.Accept(this, context); } } catch (Exception ex) { Debug.Fail(String.Format(CultureInfo.CurrentCulture, "Exception in outliner: {0}", ex.Message)); } finally { if (rootNode != null) { EditorTree.ReleaseReadLock(_treeUserId); } else { // Tree was busy. Will try again later. GuardedOperations.DispatchInvoke(() => BackgroundTask.DoTaskOnIdle(), DispatcherPriority.Normal); } } return(true); } }
private async void RefundEventHandler(BackgroundTask task) { var refundControlTask = task as TezosRefundControlTask; var swap = refundControlTask?.Swap; if (swap == null) { return; } try { await RefundAsync(swap) .ConfigureAwait(false); } catch (Exception e) { Log.Error(e, "Refund error"); } }
public void RunBackgroundTask() { using (var manager = new JobManager()) { var did_run = false; manager.Initialize(); var task = new BackgroundTask((token) => { did_run = true; }); manager.RunBackgroundTask(task); var elapsed = Utility.Threading.BlockUntil(() => did_run, 500); Assert.True(elapsed < 500); Assert.True(did_run); Assert.True(task.DidComplete); Assert.False(task.DidError); Assert.False(task.DidTimeout); } }
private void RedeemControlCanceledEventHandler(BackgroundTask task) { var redeemControlTask = task as TezosRedeemControlTask; var swap = redeemControlTask?.Swap; if (swap == null) { return; } Log.Debug("Handle redeem control canceled event for swap {@swapId}", swap.Id); TaskPerformer.EnqueueTask(new RefundTimeControlTask { Currency = Currency, RefundTimeUtc = redeemControlTask.RefundTimeUtc, Swap = swap, CompleteHandler = RefundTimeReachedEventHandler }); }
public async Task <bool> DeleteAsync(BackgroundTask task) { var document = await _repository.RetrieveSingleOrDefaultAsync(x => x.TaskId == task.Id); if (document == null) { _logger.Warn(() => "Could not delete task with ID {Id} as it was not found.", task.Id); return(false); } var deleted = await _repository.DeleteAsync(document.Id); if (!deleted) { _logger.Warn(() => "Could not delete task with ID {Id} successfully.", task.Id); return(false); } return(true); }
private void RefundTimeReachedEventHandler(BackgroundTask task) { var refundTimeControlTask = task as RefundTimeControlTask; var swap = refundTimeControlTask?.Swap; if (swap == null) { return; } Log.Debug("Refund time reached for swap {@swapId}", swap.Id); TaskPerformer.EnqueueTask(new TezosRefundControlTask { Currency = Currency, Swap = swap, CompleteHandler = RefundConfirmedEventHandler, CancelHandler = RefundEventHandler }); }
private void SwapInitiatedEventHandler(BackgroundTask task) { var initiatedControlTask = task as TezosSwapInitiatedControlTask; var swap = initiatedControlTask?.Swap; if (swap == null) { return; } Log.Debug( "Initiator's payment transaction received. Now acceptor can broadcast payment tx for swap {@swapId}", swap.Id); swap.SetHasPartyPayment(); swap.SetPartyPaymentConfirmed(); RaiseSwapUpdated(swap, SwapStateFlags.HasPartyPayment | SwapStateFlags.IsPartyPaymentConfirmed); InitiatorPaymentConfirmed?.Invoke(this, new SwapEventArgs(swap)); }
private void RedeemControlCompletedEventHandler(BackgroundTask task) { var redeemControlTask = task as TezosRedeemControlTask; var swap = redeemControlTask?.Swap; if (swap == null) { return; } Log.Debug("Handle redeem control completed event for swap {@swapId}", swap.Id); if (swap.IsAcceptor) { swap.Secret = redeemControlTask.Secret; RaiseSwapUpdated(swap, SwapStateFlags.HasSecret); RaiseAcceptorPaymentSpent(swap); } }
private void RedeemPartyControlCanceledEventHandler(BackgroundTask task) { var redeemControlTask = task as EthereumRedeemControlTask; var swap = redeemControlTask?.Swap; if (swap == null) { return; } Log.Debug("Handle redeem party control canceled event for swap {@swapId}", swap.Id); if (swap.Secret?.Length > 0) //note: using RefundTimeUtc = DefaultCounterPartyLockTimeHours, if secret is not revealed yet, counterparty is refunding in _soldcurrency side { //todo: Make some panic here Log.Error("Counter counterParty redeem need to be made for swap {@swapId}, using secret {@Secret}", swap.Id, Convert.ToBase64String(swap.Secret)); } }
private async void ForceCompareButton_Click(object sender, RoutedEventArgs e) { MainWindow.progressDialog.Show(); try { bool result = await BackgroundTask.CheckAndExcuteWebPageAsync(Item, true); MainWindow.progressDialog.Close(); if (!result) { await MainWindow.dialog.ShowInfomationAsync(FindResource("label_compareComplete") as string); } Notify(nameof(Item)); } catch (Exception ex) { MainWindow.progressDialog.Close(); await MainWindow.dialog.ShowErrorAsync(ex.ToString(), FindResource("error_compareFailed") as string); } }
public BackgroundTask Patch(BackgroundTask request) { if (true != (request?.Id > 0)) { throw new HttpError(HttpStatusCode.NotFound, "Please specify a valid Id of the BackgroundTask to patch."); } request.Select = request.Select ?? new List <string>(); BackgroundTask ret = null; using (Execute) { Execute.Run(ssn => { ret = _AssignValues(request, DocConstantPermission.EDIT, ssn); }); } return(ret); }
async void IconTapped(object sender, EventArgs e) { var image = sender as Image; //indicate each icon function in this page switch (image.StyleId) { case "phone_icon": Device.OpenUri(new Uri(String.Format("tel:{0}", jobItem.TelNo))); break; case "map_icon": Device.OpenUri(new Uri(String.Format("geo:{0}", jobItem.Latitude + "," + jobItem.Longitude))); break; case "barCode_icon": await PopupNavigation.Instance.PushAsync(new BarCodePopUp(jobCode, bookingCode)); break; case "print_icon": PrintConsigmentNote(); break; case "camera_icon": await CommonFunction.StoreImages(jobItem.EventRecordId.ToString(), this, "NormalImage"); await DisplayImage(); BackgroundTask.StartTimer(); break; case "futile_icon": await Navigation.PushAsync(new FutileTrip_CargoReturn()); break; case "confirm_icon": UpdateJob(); break; } }
public void TaskTimeout() { using (var manager = new JobManager()) { var did_run = false; var did_timeout = false; manager.Initialize(); manager.EnableHighPrecisionHeartbeat = true; manager.Start(); var task = new BackgroundTask((token) => { did_run = true; Thread.Sleep(5000); }); task.TimeoutMilliseconds = 50; task.Timeout += (sender, eventArgs) => { did_timeout = true; }; manager.RunBackgroundTask(task); var elapsed = Utility.Threading.BlockUntil(() => did_run, 500, sleepIntervalMs: 5); Assert.True(elapsed < 500); Assert.True(did_run); Assert.True(manager.JobIsRunning(task.Id)); // wait for the timeout handler ... var timeoutElapsed = Utility.Threading.BlockUntil(() => did_timeout, 500, sleepIntervalMs: 5); Assert.True(timeoutElapsed < 500); Assert.True(did_timeout); Assert.False(task.DidComplete); Assert.False(task.DidError); Assert.True(task.DidTimeout); Assert.False(manager.JobIsRunning(task.Id)); } }
// Note: you may change the name of the 'Apply' method as desired, but be sure to change the // corresponding parameter in the MenuAction and ButtonAction attributes /// <summary> /// Called by the framework when the user clicks the "apply" menu item or toolbar button. /// </summary> public void Apply() { if (!Enabled || this.Context.SelectedSingleSeries == null) { return; } List <string> seriesUIDs = new List <string>(); List <string> studyUIDs = new List <string>(); foreach (SeriesItem item in this.Context.SelectedMultipleSeries) { string foo = item.SeriesInstanceUID; Platform.Log(LogLevel.Info, foo); seriesUIDs.Add(item.SeriesInstanceUID); studyUIDs.Add(item.StudyInstanceUID); } AEInformation destination = get_server(); if (destination != null) { BackgroundTask task = new BackgroundTask( delegate(IBackgroundTaskContext context) { DicomSendServiceClient sender = new DicomSendServiceClient(); sender.Open(); SendSeriesRequest series_request = new SendSeriesRequest(); series_request.DestinationAEInformation = destination; series_request.StudyInstanceUid = studyUIDs[0]; series_request.SeriesInstanceUids = seriesUIDs; sender.SendSeries(series_request); sender.Close(); // OnMoveCompleted(); }, true); task.Run(); LocalDataStoreActivityMonitorComponentManager.ShowSendReceiveActivityComponent(this.Context.DesktopWindow); } }
private void DoPrintRequest() { string path = null; var task = new BackgroundTask( delegate(IBackgroundTaskContext taskContext) { try { taskContext.ReportProgress(new BackgroundTaskProgress(0, SR.MessageGeneratingPdf)); Platform.GetService <IReportingWorkflowService>( service => { var request = new PrintReportRequest(_reportRef) { RecipientContactPointRef = _selectedContactPoint.ContactPointRef }; var data = service.PrintReport(request).ReportPdfData; // we don't really care about the "key" here, or the time-to-live, since we won't be accesing this file ever again path = TempFileManager.Instance.CreateFile(new object(), "pdf", data, TimeSpan.FromMinutes(1)); }); taskContext.Complete(); } catch (Exception e) { taskContext.Error(e); } }, false) { ThreadUICulture = Desktop.Application.CurrentUICulture }; ProgressDialog.Show(task, this.Host.DesktopWindow, true, ProgressBarStyle.Marquee); if (path != null) { Process.Start(path); } }
/// <summary> /// Create tables used for installation /// </summary> /// <param name="level"></param> /// <param name="worker"></param> public static void CreateTable(Level level, BackgroundTask worker) { Type[] baiscTypes = CreateBasicTable(); Assembly basicAssembly = baiscTypes[0].Assembly; Assembly[] assemblies = SysExtension.GetInstalledAssemblies(); int i = 0; foreach (Assembly asm in assemblies) { MessageBuilder messages = new MessageBuilder(); foreach (Type type in asm.GetTypes()) { if (type.BaseType != typeof(DPObject)) { continue; } if (asm == basicAssembly && Array.IndexOf(baiscTypes, type) >= 0) { continue; } TableAttribute[] A = type.GetAttributes <TableAttribute>(); if (A.Length == 0) { continue; } if (A[0].Level == level) { messages.AddRange(CreateTable(type)); } } worker.ReportProgress((int)(i * 100.0 / assemblies.Length), messages.ToString()); i++; } }
public void when_cancelled_before_start_will_not_execute_the_delegate() { bool wasExecuted = false; var task = new BackgroundTask(() => wasExecuted = true); task.Cancel(); task.Start(null); Assert.That(wasExecuted, Is.False); }
public void is_not_busy_before_start() { var task = new BackgroundTask(() => null); Assert.That(task.IsBusy, Is.False); }
public void fires_complete_event_with_result_when_available() { object userState = new object(); bool wasFired = false; const int result = 8; var handle = new ManualResetEvent(false); var task = new BackgroundTask(() => result); task.Completed += (s, e) => { wasFired = true; Assert.That(e.Result, Is.EqualTo(result)); Assert.That(e.Error, Is.Null); Assert.That(e.Cancelled, Is.False); handle.Set(); }; task.Start(userState); handle.WaitOne(1000); Assert.That(wasFired, Is.True); }
public void ExcuteLater(BackgroundTask task) { tasksToExecute.Value.Add(task); this.logger.DebugFormat("Adding '{0}' to the Task Executor", task); }
public void is_not_cancelled_at_start() { var task = new BackgroundTask(() => null); Assert.That(task.CancellationPending, Is.False); }
public void fires_event_when_progress_is_updated() { const int percentage = 20; object userState = new object(); bool wasFired = false; var handle = new ManualResetEvent(false); var task = new BackgroundTask( () => { BackgroundTask.CurrentContext.ReportProgress(percentage); return null; }); task.ProgressChanged += (s, e) => { wasFired = true; Assert.That(s, Is.EqualTo(task)); Assert.That(e.ProgressPercentage, Is.EqualTo(percentage)); handle.Set(); }; task.Start(userState); handle.WaitOne(1000); Assert.That(wasFired, Is.True); }
/// <summary> /// Display the wizard page that corresponds to the current /// wizard step. /// </summary> private void DisplayActiveWizardPage() { // Check if the specified wizardStep is in range. if (wizardStep < 0 || wizardStep >= wizardPages.Count) return; this.SuspendLayout(); WizardBaseCtl previousPage = null; // Check if there was a previous wizard page. if (wizardPage != null) { task = wizardPage.BkgTask; previousPage = wizardPage; } wizardPage = wizardPages[wizardStep] as WizardBaseCtl; if (this.wizardPage != null) { // On first wizard page, disable "Back" button stepButtons.CanMoveBack = (wizardStep > 0); // On last wizard page, disable "Next" button stepButtons.CanMoveNext = (wizardStep < wizardPages.Count - 1); // On last wizard page, enable "Finish" button stepButtons.CanFinish = (wizardStep >= wizardPages.Count - 1); // Set the title bar text (e.g. "Wizard X Step 2 of 4"). // If the wizard has only one step show . if (wizardPages.Count > 1) { SetTitle(string.Format("{0} - {1} {2} {3} {4}", Translator.Translate(wizardName), Translator.Translate("TXT_WIZARDSTEPTEXT"), wizardStep + 1, Translator.Translate("TXT_WIZARDSTEPDELIMITER"), wizardPages.Count)); } else { SetTitle(Translator.Translate(wizardName)); } AddPageToForm(wizardPage); wizardPage.BkgTask = task; // Set the wizard direction wizardPage.Direction = wizardDirection; wizardPage.Focus(); this.ShowImage = wizardPage.ShowImage; this.ShowSeparator = wizardPage.ShowSeparator; } this.ResumeLayout(); if (previousPage != null) { // Set the wizard direction previousPage.Direction = wizardDirection; previousPage.ExecutePageLeaveActions(); } if (this.wizardPage != null) { // Execute the custom actions for the wizard page. // This is necessary because different actions might // be needed when moving next or back. wizardPage.ExecutePageEnterActions(); } }
/// <summary> /// Display the wizard finish page. /// </summary> private void DisplayFinishPage() { this.SuspendLayout(); WizardBaseCtl previousPage = null; // Check if there was a previous wizard page. if (wizardPage != null) { task = wizardPage.BkgTask; previousPage = wizardPage; // Remove the previous wizard page. pnlContent.Controls.Remove(wizardPage); } wizardPage = _finishPage; // Subscribe for wizard events. (wizardPage as WizFinishPageCtl).FinishPageExit += new WizFinishPageCtl.FinishPageExitEventHandler(OnFinishPageExit); // Set the title bar text. SetTitle(string.Format("{0} {1}", Translator.Translate(wizardName), Translator.Translate("TXT_WIZFINISHING"))); AddPageToForm(wizardPage); // Set the table of variables. // If this is the first wizard step then the table should be empty. wizardPage.BkgTask = task; // Set the wizard direction wizardPage.Direction = wizardDirection; if (previousPage != null) { // Set the wizard direction previousPage.Direction = wizardDirection; previousPage.ExecutePageLeaveActions(); } wizardPage.ExecutePageEnterActions(); wizardPage.Focus(); this.ResumeLayout(); }
public void fires_complete_event_when_work_is_cancelled() { object userState = new object(); bool wasFired = false; var handle = new ManualResetEvent(false); BackgroundTask task = null; task = new BackgroundTask( () => { task.Cancel(); return null; }); task.Completed += (s, e) => { wasFired = true; Assert.That(s, Is.EqualTo(task)); Assert.That(e.UserState, Is.EqualTo(userState)); Assert.That(e.Result, Is.Null); Assert.That(e.Error, Is.Null); Assert.That(e.Cancelled, Is.True); handle.Set(); }; task.Start(userState); handle.WaitOne(1000); Assert.That(wasFired, Is.True); }
/// <summary> /// Overloaded. Initializes and displays the wizard container form. /// In order to define the wizard pages, there must be created an array /// of "wizard pages types". This array must be passed to the function. /// </summary> /// <param name="wizardName">The name of the wizard, /// that will be displayed in the title bar. /// </param> /// <param name="wizardPages">The array of "wizard pages types" that /// must be passed to the function. /// </param> /// <param name="hasFinishPage">A flag indicating if the wizard should /// display a finish page.</param> /// <param name="initVariableTable">A variable list that has to be passed /// to the wizard before initialization. /// </param> /// <returns>The wizard dialog result (OK, Cancel etc).</returns> public static DialogResult CreateWizard(string wizardName, Type[] wizardPages, bool hasFinishPage, BackgroundTask initTask, Icon customIcon = null) { // Test there have been defined any wizard pages. // If not, then do not show the wizard. if (wizardPages.Length <= 0) return DialogResult.Abort; // Initialize the wizard container form WizardHostForm wizardHostForm = new WizardHostForm(); // Define the wizard pages/steps foreach (Type wizardPage in wizardPages) { wizardHostForm.AddWizardPage(wizardPage); } // Set the wizard name wizardHostForm.WizardName = wizardName; wizardHostForm.HasFinishPage = hasFinishPage; wizardHostForm.KeyPreview = false; // Display the wizard container form wizardHostForm.task = initTask; if (customIcon != null) { wizardHostForm.InheritAppIcon = false; wizardHostForm.Icon = customIcon; } try { return wizardHostForm.ShowDialog(); } catch { } return DialogResult.Cancel; }
/// <summary> /// Processes the specified work item. /// </summary> /// <param name="backgroundTask">The work item.</param> public void Process(BackgroundTask backgroundTask) { if (backgroundTask == null) { Debug.Fail("Not allowed to be null"); return; } Trace.WriteLine("Signaling processing thread to process the queued task"); queuedBackgroundTask = backgroundTask; OnPropertyChanged("QueuedBackgroundTask"); ToggleStatus(false); // Signal our processing thread to process the queued task signal.Set(); }
public void fires_complete_event_when_exception_occurs() { object userState = new object(); var exception = new Exception(); bool wasFired = false; var handle = new ManualResetEvent(false); var task = new BackgroundTask( () => { throw exception; }); task.Completed += (s, e) => { wasFired = true; Assert.That(e.Result, Is.Null); Assert.That(e.Error, Is.EqualTo(exception)); Assert.That(e.Cancelled, Is.False); handle.Set(); }; task.Start(userState); handle.WaitOne(1000); Assert.That(wasFired, Is.True); }
public void when_cancelled_during_execution_will_update_context() { BackgroundTask task = null; task = new BackgroundTask( () => { task.Cancel(); Assert.That(BackgroundTask.CurrentContext.CancellationPending, Is.True); Assert.That(task.CancellationPending, Is.True); return null; }); task.Start(null); }
/// <summary> /// Heartbeat thread, waits for signal that something has been queued for processing. /// </summary> protected virtual void Heartbeat() { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); do { if (shutdown) return; Trace.WriteLine("Processor idle, waiting for signal..."); // Wait for the signal to be set signal.WaitOne(); Trace.WriteLine("Got signal, processing task"); // Exit heartbeat if (shutdown) return; try { queuedBackgroundTask.OnStarted(); queuedBackgroundTask.Execute(); queuedBackgroundTask.OnSuccess(); } //catch (ThreadAbortException) //{ // Thread.ResetAbort(); //} catch (Exception ex) { try { Logger.Error("An error has occured while executing the task {0}, Exception = {1}", LogSource.TaskQueue, this, ex); queuedBackgroundTask.OnFailure(); } catch (Exception ex1) { Logger.Error("A fatal background task exception has occured. Exception = {0}", LogSource.TaskQueue, ex1); } } finally { try { queuedBackgroundTask.OnCompleted(); ToggleStatus(true); queuedBackgroundTask = null; OnPropertyChanged("QueuedBackgroundTask"); } catch (Exception ex) { Logger.Error("A fatal background task exception has occured. Exception = {0}", LogSource.TaskQueue, ex); } } } while (true); }
public void is_not_busy_after_work() { var task = new BackgroundTask(() => null); Assert.That(task.IsBusy, Is.False); }
public static void ExecuteLater(BackgroundTask task) { tasksToExecute.Value.Add(task); }