From 14d0ea1371a26945efa860c7fdd903c8056164c4 Mon Sep 17 00:00:00 2001 From: Markus Ewald Date: Thu, 7 Feb 2019 17:36:40 +0000 Subject: [PATCH] Added threaded action to wrap sub-actions a view model can perform (this can either be scheduled individually or on the parent threaded view model); added missing copyright statement; more unit tests git-svn-id: file:///srv/devel/repo-conversion/nuwi@45 d2e56fa2-650e-0410-a79f-9358c0239efd --- Nuclex.Windows.Forms (net-4.0).csproj | 8 + Properties/AssemblyInfo.cs | 4 +- Source/AutoBinding/ConventionBinder.cs | 70 +-- Source/AutoBinding/IAutoBinder.cs | 32 +- Source/NullActiveWindowTracker.cs | 37 ++ Source/ViewModels/DialogViewModel.Test.cs | 26 +- Source/ViewModels/ThreadedAction.Test.cs | 271 ++++++++++++ Source/ViewModels/ThreadedAction.cs | 412 ++++++++++++++++++ .../ThreadedDialogViewModel.Test.cs | 26 +- Source/ViewModels/ThreadedViewModel.Test.cs | 58 ++- Source/ViewModels/ThreadedViewModel.cs | 6 + Source/Views/IActiveWindowTracker.cs | 38 ++ Source/Views/ViewControl.cs | 10 +- Source/Views/ViewForm.cs | 10 +- Source/WindowManager.Test.cs | 21 + 15 files changed, 961 insertions(+), 68 deletions(-) create mode 100644 Source/NullActiveWindowTracker.cs create mode 100644 Source/ViewModels/ThreadedAction.Test.cs create mode 100644 Source/ViewModels/ThreadedAction.cs create mode 100644 Source/Views/IActiveWindowTracker.cs create mode 100644 Source/WindowManager.Test.cs diff --git a/Nuclex.Windows.Forms (net-4.0).csproj b/Nuclex.Windows.Forms (net-4.0).csproj index 69f8384..fbd742d 100644 --- a/Nuclex.Windows.Forms (net-4.0).csproj +++ b/Nuclex.Windows.Forms (net-4.0).csproj @@ -57,10 +57,15 @@ + DialogViewModel.cs + + + ThreadedAction.cs + ThreadedDialogViewModel.cs @@ -79,6 +84,9 @@ Form + + WindowManager.cs + ProgressReporterForm.cs Designer diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs index 6311ec0..3b320e0 100644 --- a/Properties/AssemblyInfo.cs +++ b/Properties/AssemblyInfo.cs @@ -7,9 +7,9 @@ using System.Runtime.InteropServices; // associated with an assembly. [assembly: AssemblyTitle("Nuclex.Windows.Forms")] [assembly: AssemblyProduct("Nuclex.Windows.Forms")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyDescription("Lean and elegant MVVM library with extras for WinForms")] [assembly: AssemblyCompany("Nuclex Development Labs")] -[assembly: AssemblyCopyright("Copyright © Nuclex Development Labs 2007")] +[assembly: AssemblyCopyright("Copyright © Nuclex Development Labs 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] diff --git a/Source/AutoBinding/ConventionBinder.cs b/Source/AutoBinding/ConventionBinder.cs index 3b27b59..2faab8f 100644 --- a/Source/AutoBinding/ConventionBinder.cs +++ b/Source/AutoBinding/ConventionBinder.cs @@ -4,44 +4,44 @@ using System.Windows.Forms; namespace Nuclex.Windows.Forms.AutoBinding { - /// - /// Binds a view to its model using a convention-over-configuration approach - /// - public class ConventionBinder : IAutoBinder { + /// + /// Binds a view to its model using a convention-over-configuration approach + /// + public class ConventionBinder : IAutoBinder { - /// Binds the specified view to an explicitly selected view model - /// - /// Type of view model the view will be bound to - /// - /// View that will be bound to a view model - /// View model the view will be bound to - public void Bind(Control view, TViewModel viewModel) - where TViewModel : class { - bind(view, viewModel); - } + /// Binds the specified view to an explicitly selected view model + /// + /// Type of view model the view will be bound to + /// + /// View that will be bound to a view model + /// View model the view will be bound to + public void Bind(Control view, TViewModel viewModel) + where TViewModel : class { + bind(view, viewModel); + } - /// - /// Binds the specified view to the view model specified in its DataContext - /// - /// View that will be bound - public void Bind(Control viewControl) { - IView viewControlAsView = viewControl as IView; - if(viewControlAsView == null) { - throw new InvalidOperationException( - "The specified view has no view model associated. Either assign your " + - "view model to the view's data context beforehand or use the overload " + - "of Bind() that allows you to explicitly specify the view model." - ); - } + /// + /// Binds the specified view to the view model specified in its DataContext + /// + /// View that will be bound + public void Bind(Control viewControl) { + IView viewControlAsView = viewControl as IView; + if(viewControlAsView == null) { + throw new InvalidOperationException( + "The specified view has no view model associated. Either assign your " + + "view model to the view's data context beforehand or use the overload " + + "of Bind() that allows you to explicitly specify the view model." + ); + } - bind(viewControl, viewControlAsView.DataContext); - } + bind(viewControl, viewControlAsView.DataContext); + } - /// Binds a view to a view model - /// View that will be bound - /// View model the view will be bound to - private void bind(Control view, object viewModel) { - } + /// Binds a view to a view model + /// View that will be bound + /// View model the view will be bound to + private void bind(Control view, object viewModel) { + } - } + } } // namespace Nuclex.Windows.Forms.AutoBinding diff --git a/Source/AutoBinding/IAutoBinder.cs b/Source/AutoBinding/IAutoBinder.cs index e1b514d..9220ea2 100644 --- a/Source/AutoBinding/IAutoBinder.cs +++ b/Source/AutoBinding/IAutoBinder.cs @@ -5,24 +5,24 @@ using Nuclex.Windows.Forms.Views; namespace Nuclex.Windows.Forms.AutoBinding { - /// Binds views to their view models - public interface IAutoBinder { + /// Binds views to their view models + public interface IAutoBinder { - /// Binds the specified view to an explicitly selected view model - /// - /// Type of view model the view will be bound to - /// - /// View that will be bound to a view model - /// View model the view will be bound to - void Bind(Control view, TViewModel viewModel) - where TViewModel : class; + /// Binds the specified view to an explicitly selected view model + /// + /// Type of view model the view will be bound to + /// + /// View that will be bound to a view model + /// View model the view will be bound to + void Bind(Control view, TViewModel viewModel) + where TViewModel : class; - /// - /// Binds the specified view to the view model specified in its DataContext - /// - /// View that will be bound - void Bind(Control view); + /// + /// Binds the specified view to the view model specified in its DataContext + /// + /// View that will be bound + void Bind(Control view); - } + } } // namespace Nuclex.Windows.Forms.AutoBinding diff --git a/Source/NullActiveWindowTracker.cs b/Source/NullActiveWindowTracker.cs new file mode 100644 index 0000000..c5ebd03 --- /dev/null +++ b/Source/NullActiveWindowTracker.cs @@ -0,0 +1,37 @@ +#region CPL License +/* +Nuclex Framework +Copyright (C) 2002-2019 Nuclex Development Labs + +This library is free software; you can redistribute it and/or +modify it under the terms of the IBM Common Public License as +published by the IBM Corporation; either version 1.0 of the +License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +IBM Common Public License for more details. + +You should have received a copy of the IBM Common Public +License along with this library +*/ +#endregion + +using System; +using System.Windows.Forms; + +namespace Nuclex.Windows.Forms { + + /// Dummy implementation of the active window tracker service + internal class NullActiveWindowTracker : IActiveWindowTracker { + + /// The default instance of the dummy window tracker + public static readonly NullActiveWindowTracker Default = new NullActiveWindowTracker(); + + /// The currently active top-level or modal window + public Form ActiveWindow { get { return null; } } + + } + +} // namespace Nuclex.Windows.Forms diff --git a/Source/ViewModels/DialogViewModel.Test.cs b/Source/ViewModels/DialogViewModel.Test.cs index 00b1ba1..bb015f2 100644 --- a/Source/ViewModels/DialogViewModel.Test.cs +++ b/Source/ViewModels/DialogViewModel.Test.cs @@ -1,4 +1,26 @@ -using System; +#region CPL License +/* +Nuclex Framework +Copyright (C) 2002-2019 Nuclex Development Labs + +This library is free software; you can redistribute it and/or +modify it under the terms of the IBM Common Public License as +published by the IBM Corporation; either version 1.0 of the +License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +IBM Common Public License for more details. + +You should have received a copy of the IBM Common Public +License along with this library +*/ +#endregion + +#if UNITTEST + +using System; using NUnit.Framework; @@ -130,3 +152,5 @@ namespace Nuclex.Windows.Forms.ViewModels { } } // namespace Nuclex.Windows.Forms.ViewModels + +#endif // UNITTEST diff --git a/Source/ViewModels/ThreadedAction.Test.cs b/Source/ViewModels/ThreadedAction.Test.cs new file mode 100644 index 0000000..b00929f --- /dev/null +++ b/Source/ViewModels/ThreadedAction.Test.cs @@ -0,0 +1,271 @@ +#region CPL License +/* +Nuclex Framework +Copyright (C) 2002-2019 Nuclex Development Labs + +This library is free software; you can redistribute it and/or +modify it under the terms of the IBM Common Public License as +published by the IBM Corporation; either version 1.0 of the +License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +IBM Common Public License for more details. + +You should have received a copy of the IBM Common Public +License along with this library +*/ +#endregion + +#if UNITTEST + +using System; +using System.ComponentModel; +using System.Threading; + +using NUnit.Framework; + +namespace Nuclex.Windows.Forms.ViewModels { + + /// Unit test for the threaded action class + [TestFixture] + public class ThreadedActionTest { + + #region class DummyContext + + /// Synchronization context that does absolutely nothing + private class DummyContext : ISynchronizeInvoke { + + #region class SimpleAsyncResult + + /// Barebones implementation of an asynchronous result + private class SimpleAsyncResult : IAsyncResult { + + /// Ehether the asynchronous operation is complete + /// + /// Always true because it completes synchronously + /// + public bool IsCompleted { get { return true; } } + + /// + /// Wait handle that can be used to wait for the asynchronous operation + /// + public WaitHandle AsyncWaitHandle { + get { throw new NotImplementedException("Not implemented"); } + } + + /// Custom state that can be used to pass information around + public object AsyncState { + get { throw new NotImplementedException("Not implemented"); } + } + + /// Whether the asynchronous operation completed synchronously + public bool CompletedSynchronously { get { return true; } } + + /// The value returned from the asynchronous operation + public object ReturnedValue; + + } + + #endregion // class SimpleAsyncResult + + /// Whether the calling thread needs to use Invoke() + public bool InvokeRequired { + get { return true; } + } + + /// Schedules the specified method for execution in the target thread + /// Method the target thread will execute when it is idle + /// Arguments that will be passed to the method + /// + /// An asynchronous result handle that can be used to check on the status of + /// the call and wait for its completion + /// + public IAsyncResult BeginInvoke(Delegate method, object[] arguments) { + var asyncResult = new SimpleAsyncResult(); + asyncResult.ReturnedValue = method.Method.Invoke(method.Target, arguments); + return asyncResult; + } + + /// Waits for the asychronous call to complete + /// + /// Asynchronous result handle returned by the method + /// + /// The original result returned by the asychronously called method + public object EndInvoke(IAsyncResult result) { + return ((SimpleAsyncResult)result).ReturnedValue; + } + + /// + /// Schedules the specified method for execution in the target thread and waits + /// for it to complete + /// + /// Method that will be executed by the target thread + /// Arguments that will be passed to the method + /// The result returned by the specified method + public object Invoke(Delegate method, object[] arguments) { + return method.Method.Invoke(method.Target, arguments); + } + + } + + #endregion // class DummyContext + + #region class DummyThreadedAction + + /// Implementation of a threaded action for the unit test + private class DummyThreadedAction : ThreadedAction { + + /// + /// Initializes a new threaded action, letting the base class figure out the UI thread + /// + public DummyThreadedAction() : base() { + this.finishedGate = new ManualResetEvent(initialState: false); + } + + /// + /// Initializes a new view model using the specified UI context explicitly + /// + public DummyThreadedAction(ISynchronizeInvoke uiContext) : base(uiContext) { + this.finishedGate = new ManualResetEvent(initialState: false); + } + + /// Immediately releases all resources owned by the instance + public override void Dispose() { + base.Dispose(); + + if(this.finishedGate != null) { + this.finishedGate.Dispose(); + this.finishedGate = null; + } + } + + /// Waits until the first background operation is finished + /// + /// True if the background operation is finished, false if it is ongoing + /// + public bool WaitUntilFinished() { + return this.finishedGate.WaitOne(100); + } + + /// Selects the value that will be assigned when the action runs + /// Value the action will assigned when it runs + public void SetValueToAssign(int valueToAssign) { + this.valueToAssign = valueToAssign; + } + + /// Sets up an error the action will fail with when run + /// Error the action will fail with + public void SetErrorToFailWith(Exception errorToFailWith) { + this.errorToFailWith = errorToFailWith; + } + + /// Last error that was reported by the threaded view model + public Exception ReportedError { + get { return this.reportedError; } + } + + /// Value that has been assigned from the background thread + public int AssignedValue { + get { return this.assignedValue; } + } + + /// Executes the threaded action from the background thread + /// Token by which execution can be canceled + protected override void Run(CancellationToken cancellationToken) { + if(this.errorToFailWith != null) { + throw this.errorToFailWith; + } + + this.assignedValue = this.valueToAssign; + this.finishedGate.Set(); + } + + /// Called when an error occurs in the background thread + /// Exception that was thrown in the background thread + protected override void ReportError(Exception exception) { + this.reportedError = exception; + this.finishedGate.Set(); + } + + /// Error the action will fail with, if set + private Exception errorToFailWith; + /// Value the action will assign to its same-named field + private int valueToAssign; + + /// Last error that was reported by the threaded view model + private volatile Exception reportedError; + /// Triggered when the + private ManualResetEvent finishedGate; + /// Value that is assigned through the background thread + private volatile int assignedValue; + + } + + #endregion // class DummyThreadedAction + + /// Verifies that the threaded action has a default constructor + [Test, Explicit] + public void HasDefaultConstructor() { + using(var mainForm = new System.Windows.Forms.Form()) { + mainForm.Show(); + try { + mainForm.Visible = false; + using(new DummyThreadedAction()) { } + } + finally { + mainForm.Close(); + } + } + } + + /// + /// Verifies that the threaded action can be constructed with a custom UI context + /// + [Test] + public void HasCustomSychronizationContextConstructor() { + using(new DummyThreadedAction(new DummyContext())) { } + } + + /// Checks that a new threadd action starts out idle and not busy + [Test] + public void NewInstanceIsNotBusy() { + using(var action = new DummyThreadedAction(new DummyContext())) { + Assert.IsFalse(action.IsBusy); + } + } + + /// + /// Verifies that errors happening in the background processing threads are + /// reported to the main thread + /// + [Test] + public void ErrorsInBackgroundThreadAreReported() { + using(var action = new DummyThreadedAction(new DummyContext())) { + var testError = new ArgumentException("Mooh"); + action.SetErrorToFailWith(testError); + action.Start(); + action.WaitUntilFinished(); + Assert.AreSame(testError, action.ReportedError); + } + } + + /// + /// Verifies that the background thread actually executes and can do work + /// + [Test] + public void BackgroundThreadExecutesTasks() { + using(var action = new DummyThreadedAction(new DummyContext())) { + action.SetValueToAssign(42001); + action.Start(); + action.WaitUntilFinished(); + Assert.AreEqual(42001, action.AssignedValue); + } + } + + } + +} // namespace Nuclex.Windows.Forms.ViewModels + +#endif // UNITTEST \ No newline at end of file diff --git a/Source/ViewModels/ThreadedAction.cs b/Source/ViewModels/ThreadedAction.cs new file mode 100644 index 0000000..bd73231 --- /dev/null +++ b/Source/ViewModels/ThreadedAction.cs @@ -0,0 +1,412 @@ +#region CPL License +/* +Nuclex Framework +Copyright (C) 2002-2019 Nuclex Development Labs + +This library is free software; you can redistribute it and/or +modify it under the terms of the IBM Common Public License as +published by the IBM Corporation; either version 1.0 of the +License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +IBM Common Public License for more details. + +You should have received a copy of the IBM Common Public +License along with this library +*/ +#endregion + +using System; +using System.ComponentModel; +using System.Threading; +using System.Windows.Forms; + +using Nuclex.Support; +using Nuclex.Support.Threading; + +// Possible problem: +// +// After Run() is called, the action may not actually run if +// it is using another thread runner and that one is cancelled. +// +// Thus, a second call to Run() has to schedule the action again, +// even if it might already be scheduled, but should also not execute +// the action a second time if is was indeed still scheduled. + +namespace Nuclex.Windows.Forms.ViewModels { + + /// Encapsulates an action that can run in a thread + /// + /// + /// Sometimes a view model wants to allow multiple actions to take place + /// at the same time. Think multiple panels on the view require updating + /// from a web service - you can make both requests at the same time + /// instead of sequentially. + /// + /// + /// This class is also of use for things that need to be done sequentially + /// by sharing the thread runner of the threaded view model. That way, + /// you still have cancellable actions you can run at will and they + /// automatically queue themselves to be executed one after another. + /// + /// + public abstract class ThreadedAction : Observable, IDisposable { + + #region class ThreadedActionThreadRunner + + /// Thread runner for the threaded action + private class ThreadedActionThreadRunner : ThreadRunner { + + /// Initializes a new thread runner for the threaded view model + public ThreadedActionThreadRunner(ThreadedAction viewModel) { + this.threadedAction = viewModel; + } + + /// Reports an error + /// Error that will be reported + protected override void ReportError(Exception exception) { + this.threadedAction.reportErrorFromThread(exception); + } + + /// Called when the status of the busy flag changes + protected override void BusyChanged() { + // Narf. Can't use this. + } + + /// View model the thread runner belongs to + private ThreadedAction threadedAction; + + } + + #endregion // class ThreadedActionThreadRunner + + /// Initializes all common fields of the instance + private ThreadedAction() { + this.callRunIfNotCancelledDelegate = new Action( + callThreadedExecuteIfNotCancelled + ); + this.reportErrorDelegate = new Action(ReportError); + } + + /// Initializes a threaded action that uses its own thread runner + public ThreadedAction(ISynchronizeInvoke uiContext = null) : this() { + if(uiContext == null) { + this.uiContext = getMainWindow(); + } else { + this.uiContext = uiContext; + } + + this.ownThreadRunner = new ThreadedActionThreadRunner(this); + } + + /// + /// Initializes a threaded action that uses the view model's thread runner + /// + /// View model whose thread runner will be used + /// + /// UI dispatcher that can be used to run callbacks in the UI thread + /// + public ThreadedAction( + ThreadedViewModel viewModel, ISynchronizeInvoke uiContext = null + ) : this() { + if(uiContext == null) { + this.uiContext = getMainWindow(); + } else { + this.uiContext = uiContext; + } + + this.externalThreadRunner = viewModel.ThreadRunner; + } + + /// Immediately releases all resources owned by the instance + public virtual void Dispose() { + if(this.isBusy) { + Cancel(); + } + if(this.ownThreadRunner != null) { + this.ownThreadRunner.Dispose(); + this.ownThreadRunner = null; + } + if(this.currentCancellationTokenSource != null) { + this.currentCancellationTokenSource.Dispose(); + this.currentCancellationTokenSource = null; + } + } + + /// Whether the view model is currently busy executing a task + public bool IsBusy { + get { return this.isBusy; } + private set { + if(value != this.isBusy) { + this.isBusy = value; + OnPropertyChanged(nameof(IsBusy)); + } + } + } + + /// Cancels the running background task, if any + public void Cancel() { + lock(this.runningTaskSyncRoot) { + + // If the background task is not running, do nothing. This also allows + // us to avoid needless recreation of the same cancellation token source. + if(!this.isBusy) { + return; + } + + // If a task is currently running, cancel it + if(this.isRunning) { + if(this.currentCancellationTokenSource != null) { + this.currentCancellationTokenSource.Cancel(); + this.currentCancellationTokenSource = null; + } + } + + // If the task was scheduled to be repeated, we also have to mark + // the upcoming cancellation token source as canceled because the scheduled + // run will still be happening (it will just cancel out immediately). + if(this.nextCancellationTokenSource != null) { + this.nextCancellationTokenSource.Cancel(); + this.nextCancellationTokenSource = null; + } + this.isScheduledAgain = false; + + // If the task was not running, we can clear the busy state because it + // is not going to reach the running state. + if(!this.isRunning) { + this.isBusy = false; + } + + } + } + + /// + /// Starts the task, cancelling the running task before doing so + /// + public void Restart() { + bool reportBusyChange = false; + + lock(this.runningTaskSyncRoot) { + + // If we're already in the execution phase, schedule another execution right + // after this one is finished (because now, data might have changed after + // execution has finished). + if(this.isRunning) { + //System.Diagnostics.Debug.WriteLine("Restart() - interrupting execution"); + if(this.currentCancellationTokenSource != null) { + this.currentCancellationTokenSource.Cancel(); + } + + this.currentCancellationTokenSource = this.nextCancellationTokenSource; + this.nextCancellationTokenSource = null; + this.isScheduledAgain = false; + } + + // If there's no cancellation token source, create one. If an execution + // was already scheduled and the cancellation token source is still valid, + // then reuse that in order to be able to cancel all scheduled executions. + if(this.currentCancellationTokenSource == null) { + //System.Diagnostics.Debug.WriteLine("Restart() - creating new cancellation token"); + this.currentCancellationTokenSource = new CancellationTokenSource(); + } + + // Schedule another execution of the action + scheduleExecution(); + + reportBusyChange = (this.isBusy == false); + this.isBusy = true; + } + + if(reportBusyChange) { + OnPropertyChanged(nameof(IsBusy)); + } + } + + /// Starts the task + public void Start() { + bool reportBusyChange = false; + + lock(this.runningTaskSyncRoot) { + + // If we're already in the execution phase, schedule another execution right + // after this one is finished (because now, data might have changed after + // execution has finished). + if(this.isRunning) { + + // If we already created a new cancellation token source, keep it, + // otherwise create a new one for the next execution + if(!this.isScheduledAgain) { + this.nextCancellationTokenSource = new CancellationTokenSource(); + this.isScheduledAgain = true; + } + + } else { + + // If there's no cancellation token source, create one. If an execution + // was already scheduled and the cancellation token source is still valid, + // then reuse that in order to be able to cancel all scheduled executions. + if(this.currentCancellationTokenSource == null) { + this.currentCancellationTokenSource = new CancellationTokenSource(); + } + + // Schedule another execution of the action + scheduleExecution(); + + } + + reportBusyChange = (this.isBusy == false); + this.isBusy = true; + } + + if(reportBusyChange) { + OnPropertyChanged(nameof(IsBusy)); + } + } + + /// Reports an error + /// Error that will be reported + protected abstract void ReportError(Exception exception); + + /// Executes the threaded action from the background thread + /// Token by which execution can be canceled + protected abstract void Run(CancellationToken cancellationToken); + + /// + /// Calls the Run() method from the background thread and manages the flags + /// + /// + private void callThreadedExecuteIfNotCancelled( + CancellationTokenSource cancellationTokenSource + ) { + lock(this) { + if(cancellationTokenSource.Token.IsCancellationRequested) { + return; + } + + this.isRunning = true; + } + + try { + Run(cancellationTokenSource.Token); + } + finally { + bool reportBusyChange = false; + + lock(this) { + this.isRunning = false; + + // Cancel the current cancellation token because this execution may have + // been scheduled multiple times (there's no way for the Run() method to + // know if the currently scheduled execution was cancelled, so it is forced + // to reschedule on each call - accepting redundant schedules). + cancellationTokenSource.Cancel(); + + // Pick the next cancellation token source. Normally it is null, but this + // is more elegant because we can avoid an while if statement this way :) + this.currentCancellationTokenSource = nextCancellationTokenSource; + this.nextCancellationTokenSource = null; + + // If Start() was called while we were executing, another execution is required + // (because the data may have changed during the call to Start()). + if(this.isScheduledAgain) { + this.isScheduledAgain = false; + scheduleExecution(); + } else { // We're idle now + reportBusyChange = (this.isBusy == true); + this.isBusy = false; + } + } + + if(reportBusyChange) { + OnPropertyChanged(nameof(IsBusy)); + } + } + } + + /// Schedules one execution of the action + private void scheduleExecution() { + //System.Diagnostics.Debug.WriteLine("Scheduling execution"); + + ThreadRunner runner = this.externalThreadRunner; + if(runner != null) { + runner.RunInBackground( + this.callRunIfNotCancelledDelegate, this.currentCancellationTokenSource + ); + } + + runner = this.ownThreadRunner; + if(runner != null) { + runner.RunInBackground( + this.callRunIfNotCancelledDelegate, this.currentCancellationTokenSource + ); + } + } + + /// Reports an error that occurred in the runner's background thread + /// Exception that the thread has encountered + private void reportErrorFromThread(Exception exception) { + this.uiContext.Invoke(this.reportErrorDelegate, new object[1] { exception }); + } + + /// Finds the application's main window + /// Main window of the application + private static Form getMainWindow() { + IntPtr mainWindowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; + + // We can get two things: a list of all open windows and the handle of + // the window that the process has registered as main window. Use the latter + // to pick the correct window from the former. + FormCollection openForms = Application.OpenForms; + int openFormCount = openForms.Count; + for(int index = 0; index < openFormCount; ++index) { + if(openForms[index].IsHandleCreated) { + if(openForms[index].Handle == mainWindowHandle) { + return openForms[index]; + } + } + } + + // No matching main window found: use the first one in good faith or fail. + if(openFormCount > 0) { + return openForms[0]; + } else { + return null; + } + } + + /// Synchronization context of the thread in which the view runs + private ISynchronizeInvoke uiContext; + /// Delegate for the ReportError() method + private Action reportErrorDelegate; + /// Delegate for the callThreadedExecuteIfNotCancelled() method + private Action callRunIfNotCancelledDelegate; + + /// Thread runner on which the action can run its background task + private ThreadedActionThreadRunner ownThreadRunner; + /// + /// External thread runner on which the action runs its background task if assigned + /// + private ThreadRunner externalThreadRunner; + + /// Synchronization root for the threaded execute method + private object runningTaskSyncRoot = new object(); + /// Used to cancel the currently running task + private CancellationTokenSource currentCancellationTokenSource; + /// Used to cancel the upcoming task if a re-run was scheduled + private CancellationTokenSource nextCancellationTokenSource; + /// Whether the background task is running or waiting to run + private volatile bool isBusy; + /// Whether execution is taking place right now + /// + /// If this flag is set and the Start() method is called, another run needs to + /// be scheduled. + /// + private bool isRunning; + /// Whether run was called while the action was already running + private bool isScheduledAgain; + + } + +} // namespace Nuclex.Windows.Forms.ViewModels diff --git a/Source/ViewModels/ThreadedDialogViewModel.Test.cs b/Source/ViewModels/ThreadedDialogViewModel.Test.cs index ae9eda2..dbf3c00 100644 --- a/Source/ViewModels/ThreadedDialogViewModel.Test.cs +++ b/Source/ViewModels/ThreadedDialogViewModel.Test.cs @@ -1,4 +1,26 @@ -using System; +#region CPL License +/* +Nuclex Framework +Copyright (C) 2002-2019 Nuclex Development Labs + +This library is free software; you can redistribute it and/or +modify it under the terms of the IBM Common Public License as +published by the IBM Corporation; either version 1.0 of the +License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +IBM Common Public License for more details. + +You should have received a copy of the IBM Common Public +License along with this library +*/ +#endregion + +#if UNITTEST + +using System; using NUnit.Framework; @@ -148,3 +170,5 @@ namespace Nuclex.Windows.Forms.ViewModels { } } // namespace Nuclex.Windows.Forms.ViewModels + +#endif // UNITTEST diff --git a/Source/ViewModels/ThreadedViewModel.Test.cs b/Source/ViewModels/ThreadedViewModel.Test.cs index 902886e..0431150 100644 --- a/Source/ViewModels/ThreadedViewModel.Test.cs +++ b/Source/ViewModels/ThreadedViewModel.Test.cs @@ -1,4 +1,24 @@ -#if UNITTEST +#region CPL License +/* +Nuclex Framework +Copyright (C) 2002-2019 Nuclex Development Labs + +This library is free software; you can redistribute it and/or +modify it under the terms of the IBM Common Public License as +published by the IBM Corporation; either version 1.0 of the +License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +IBM Common Public License for more details. + +You should have received a copy of the IBM Common Public +License along with this library +*/ +#endregion + +#if UNITTEST using System; using System.ComponentModel; @@ -135,11 +155,29 @@ namespace Nuclex.Windows.Forms.ViewModels { RunInBackground(() => throw error); } + /// + /// Assigns the specified value to the same-named property from a background thread + /// + /// Value that will be assigned to the same-named property + public void AssignValueInBackgroundThread(int value) { + RunInBackground( + delegate () { + this.assignedValue = value; + this.finishedGate.Set(); + } + ); + } + /// Last error that was reported by the threaded view model public Exception ReportedError { get { return this.reportedError; } } + /// Value that has been assigned from the background thread + public int AssignedValue { + get { return this.assignedValue; } + } + /// Called when an error occurs in the background thread /// Exception that was thrown in the background thread protected override void ReportError(Exception exception) { @@ -148,16 +186,18 @@ namespace Nuclex.Windows.Forms.ViewModels { } /// Last error that was reported by the threaded view model - private Exception reportedError; + private volatile Exception reportedError; /// Triggered when the private ManualResetEvent finishedGate; + /// Value that is assigned through the background thread + private volatile int assignedValue; } #endregion // class TestViewModel /// Verifies that the threaded view model has a default constructor - [Test] + [Test, Explicit] public void HasDefaultConstructor() { using(var mainForm = new System.Windows.Forms.Form()) { mainForm.Show(); @@ -201,6 +241,18 @@ namespace Nuclex.Windows.Forms.ViewModels { } } + /// + /// Verifies that the background thread actually executes and can do work + /// + [Test] + public void BackgroundThreadExecutesTasks() { + using(var viewModel = new TestViewModel(new DummyContext())) { + viewModel.AssignValueInBackgroundThread(10042); + viewModel.WaitUntilFinished(); + Assert.AreEqual(10042, viewModel.AssignedValue); + } + } + } } // namespace Nuclex.Windows.Forms.ViewModels diff --git a/Source/ViewModels/ThreadedViewModel.cs b/Source/ViewModels/ThreadedViewModel.cs index b321ded..c6a18f4 100644 --- a/Source/ViewModels/ThreadedViewModel.cs +++ b/Source/ViewModels/ThreadedViewModel.cs @@ -196,6 +196,12 @@ namespace Nuclex.Windows.Forms.ViewModels { OnPropertyChanged(nameof(IsBusy)); } + // For the ThreadedAction class - there should be a better way! + /// Thread runner that manages the view model's thread + internal ThreadRunner ThreadRunner { + get { return this.threadRunner; } + } + /// Reports an error that occurred in the runner's background thread /// Exception that the thread has encountered private void reportErrorFromThread(Exception exception) { diff --git a/Source/Views/IActiveWindowTracker.cs b/Source/Views/IActiveWindowTracker.cs new file mode 100644 index 0000000..ad6e56d --- /dev/null +++ b/Source/Views/IActiveWindowTracker.cs @@ -0,0 +1,38 @@ +#region CPL License +/* +Nuclex Framework +Copyright (C) 2002-2019 Nuclex Development Labs + +This library is free software; you can redistribute it and/or +modify it under the terms of the IBM Common Public License as +published by the IBM Corporation; either version 1.0 of the +License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +IBM Common Public License for more details. + +You should have received a copy of the IBM Common Public +License along with this library +*/ +#endregion + +using System; +using System.Windows.Forms; + +namespace Nuclex.Windows.Forms { + + /// Enables consumer to look up the currently active window + public interface IActiveWindowTracker { + + /// The currently active top-level or modal window + /// + /// If windows live in multiple threads, the property change notification for + /// this property, if supported, might be fired from a different thread. + /// + Form ActiveWindow { get; } + + } + +} // namespace Nuclex.Windows.Forms diff --git a/Source/Views/ViewControl.cs b/Source/Views/ViewControl.cs index e8ea3b9..f86f4bd 100644 --- a/Source/Views/ViewControl.cs +++ b/Source/Views/ViewControl.cs @@ -36,11 +36,11 @@ namespace Nuclex.Windows.Forms.Views { this.onViewModelPropertyChangedDelegate = OnViewModelPropertyChanged; } - /// Called when the control's data context is changed - /// Control whose data context was changed - /// Data context that was previously used - /// Data context that will be used from now on - protected virtual void OnDataContextChanged( + /// Called when the control's data context is changed + /// Control whose data context was changed + /// Data context that was previously used + /// Data context that will be used from now on + protected virtual void OnDataContextChanged( object sender, object oldDataContext, object newDataContext ) { var oldViewModel = oldDataContext as INotifyPropertyChanged; diff --git a/Source/Views/ViewForm.cs b/Source/Views/ViewForm.cs index f9aa329..4238ebf 100644 --- a/Source/Views/ViewForm.cs +++ b/Source/Views/ViewForm.cs @@ -36,11 +36,11 @@ namespace Nuclex.Windows.Forms.Views { this.onViewModelPropertyChangedDelegate = OnViewModelPropertyChanged; } - /// Called when the window's data context is changed - /// Window whose data context was changed - /// Data context that was previously used - /// Data context that will be used from now on - protected virtual void OnDataContextChanged( + /// Called when the window's data context is changed + /// Window whose data context was changed + /// Data context that was previously used + /// Data context that will be used from now on + protected virtual void OnDataContextChanged( object sender, object oldDataContext, object newDataContext ) { var oldViewModel = oldDataContext as INotifyPropertyChanged; diff --git a/Source/WindowManager.Test.cs b/Source/WindowManager.Test.cs new file mode 100644 index 0000000..1f44fcf --- /dev/null +++ b/Source/WindowManager.Test.cs @@ -0,0 +1,21 @@ +using System; + +using NUnit.Framework; + +namespace Nuclex.Windows.Forms { + + /// Unit test for the window manager + [TestFixture] + public class WindowManagerTest { + + /// Verifies that the window manager provides a default constructor + [Test] + public void HasDefaultConstructor() { + Assert.DoesNotThrow( + () => new WindowManager() + ); + } + + } + +} // namespace Nuclex.Windows.Forms