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
This commit is contained in:
Markus Ewald 2019-02-07 17:36:40 +00:00
parent 9aa64c4dac
commit 14d0ea1371
15 changed files with 961 additions and 68 deletions

View File

@ -57,10 +57,15 @@
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Source\AutoBinding\ConventionBinder.cs" /> <Compile Include="Source\AutoBinding\ConventionBinder.cs" />
<Compile Include="Source\AutoBinding\IAutoBinder.cs" /> <Compile Include="Source\AutoBinding\IAutoBinder.cs" />
<Compile Include="Source\NullActiveWindowTracker.cs" />
<Compile Include="Source\ViewModels\DialogViewModel.cs" /> <Compile Include="Source\ViewModels\DialogViewModel.cs" />
<Compile Include="Source\ViewModels\DialogViewModel.Test.cs"> <Compile Include="Source\ViewModels\DialogViewModel.Test.cs">
<DependentUpon>DialogViewModel.cs</DependentUpon> <DependentUpon>DialogViewModel.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="Source\ViewModels\ThreadedAction.cs" />
<Compile Include="Source\ViewModels\ThreadedAction.Test.cs">
<DependentUpon>ThreadedAction.cs</DependentUpon>
</Compile>
<Compile Include="Source\ViewModels\ThreadedDialogViewModel.cs" /> <Compile Include="Source\ViewModels\ThreadedDialogViewModel.cs" />
<Compile Include="Source\ViewModels\ThreadedDialogViewModel.Test.cs"> <Compile Include="Source\ViewModels\ThreadedDialogViewModel.Test.cs">
<DependentUpon>ThreadedDialogViewModel.cs</DependentUpon> <DependentUpon>ThreadedDialogViewModel.cs</DependentUpon>
@ -79,6 +84,9 @@
<SubType>Form</SubType> <SubType>Form</SubType>
</Compile> </Compile>
<Compile Include="Source\WindowManager.cs" /> <Compile Include="Source\WindowManager.cs" />
<Compile Include="Source\WindowManager.Test.cs">
<DependentUpon>WindowManager.cs</DependentUpon>
</Compile>
<EmbeddedResource Include="Source\ProgressReporter\ProgressReporterForm.resx"> <EmbeddedResource Include="Source\ProgressReporter\ProgressReporterForm.resx">
<DependentUpon>ProgressReporterForm.cs</DependentUpon> <DependentUpon>ProgressReporterForm.cs</DependentUpon>
<SubType>Designer</SubType> <SubType>Designer</SubType>

View File

@ -7,9 +7,9 @@ using System.Runtime.InteropServices;
// associated with an assembly. // associated with an assembly.
[assembly: AssemblyTitle("Nuclex.Windows.Forms")] [assembly: AssemblyTitle("Nuclex.Windows.Forms")]
[assembly: AssemblyProduct("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: AssemblyCompany("Nuclex Development Labs")]
[assembly: AssemblyCopyright("Copyright © Nuclex Development Labs 2007")] [assembly: AssemblyCopyright("Copyright © Nuclex Development Labs 2019")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]

View File

@ -4,44 +4,44 @@ using System.Windows.Forms;
namespace Nuclex.Windows.Forms.AutoBinding { namespace Nuclex.Windows.Forms.AutoBinding {
/// <summary> /// <summary>
/// Binds a view to its model using a convention-over-configuration approach /// Binds a view to its model using a convention-over-configuration approach
/// </summary> /// </summary>
public class ConventionBinder : IAutoBinder { public class ConventionBinder : IAutoBinder {
/// <summary>Binds the specified view to an explicitly selected view model</summary> /// <summary>Binds the specified view to an explicitly selected view model</summary>
/// <typeparam name="TViewModel"> /// <typeparam name="TViewModel">
/// Type of view model the view will be bound to /// Type of view model the view will be bound to
/// </typeparam> /// </typeparam>
/// <param name="view">View that will be bound to a view model</param> /// <param name="view">View that will be bound to a view model</param>
/// <param name="viewModel">View model the view will be bound to</param> /// <param name="viewModel">View model the view will be bound to</param>
public void Bind<TViewModel>(Control view, TViewModel viewModel) public void Bind<TViewModel>(Control view, TViewModel viewModel)
where TViewModel : class { where TViewModel : class {
bind(view, viewModel); bind(view, viewModel);
} }
/// <summary> /// <summary>
/// Binds the specified view to the view model specified in its DataContext /// Binds the specified view to the view model specified in its DataContext
/// </summary> /// </summary>
/// <param name="viewControl">View that will be bound</param> /// <param name="viewControl">View that will be bound</param>
public void Bind(Control viewControl) { public void Bind(Control viewControl) {
IView viewControlAsView = viewControl as IView; IView viewControlAsView = viewControl as IView;
if(viewControlAsView == null) { if(viewControlAsView == null) {
throw new InvalidOperationException( throw new InvalidOperationException(
"The specified view has no view model associated. Either assign your " + "The specified view has no view model associated. Either assign your " +
"view model to the view's data context beforehand or use the overload " + "view model to the view's data context beforehand or use the overload " +
"of Bind() that allows you to explicitly specify the view model." "of Bind() that allows you to explicitly specify the view model."
); );
} }
bind(viewControl, viewControlAsView.DataContext); bind(viewControl, viewControlAsView.DataContext);
} }
/// <summary>Binds a view to a view model</summary> /// <summary>Binds a view to a view model</summary>
/// <param name="view">View that will be bound</param> /// <param name="view">View that will be bound</param>
/// <param name="viewModel">View model the view will be bound to</param> /// <param name="viewModel">View model the view will be bound to</param>
private void bind(Control view, object viewModel) { private void bind(Control view, object viewModel) {
} }
} }
} // namespace Nuclex.Windows.Forms.AutoBinding } // namespace Nuclex.Windows.Forms.AutoBinding

View File

@ -5,24 +5,24 @@ using Nuclex.Windows.Forms.Views;
namespace Nuclex.Windows.Forms.AutoBinding { namespace Nuclex.Windows.Forms.AutoBinding {
/// <summary>Binds views to their view models</summary> /// <summary>Binds views to their view models</summary>
public interface IAutoBinder { public interface IAutoBinder {
/// <summary>Binds the specified view to an explicitly selected view model</summary> /// <summary>Binds the specified view to an explicitly selected view model</summary>
/// <typeparam name="TViewModel"> /// <typeparam name="TViewModel">
/// Type of view model the view will be bound to /// Type of view model the view will be bound to
/// </typeparam> /// </typeparam>
/// <param name="view">View that will be bound to a view model</param> /// <param name="view">View that will be bound to a view model</param>
/// <param name="viewModel">View model the view will be bound to</param> /// <param name="viewModel">View model the view will be bound to</param>
void Bind<TViewModel>(Control view, TViewModel viewModel) void Bind<TViewModel>(Control view, TViewModel viewModel)
where TViewModel : class; where TViewModel : class;
/// <summary> /// <summary>
/// Binds the specified view to the view model specified in its DataContext /// Binds the specified view to the view model specified in its DataContext
/// </summary> /// </summary>
/// <param name="view">View that will be bound</param> /// <param name="view">View that will be bound</param>
void Bind(Control view); void Bind(Control view);
} }
} // namespace Nuclex.Windows.Forms.AutoBinding } // namespace Nuclex.Windows.Forms.AutoBinding

View File

@ -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 {
/// <summary>Dummy implementation of the active window tracker service</summary>
internal class NullActiveWindowTracker : IActiveWindowTracker {
/// <summary>The default instance of the dummy window tracker</summary>
public static readonly NullActiveWindowTracker Default = new NullActiveWindowTracker();
/// <summary>The currently active top-level or modal window</summary>
public Form ActiveWindow { get { return null; } }
}
} // namespace Nuclex.Windows.Forms

View File

@ -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; using NUnit.Framework;
@ -130,3 +152,5 @@ namespace Nuclex.Windows.Forms.ViewModels {
} }
} // namespace Nuclex.Windows.Forms.ViewModels } // namespace Nuclex.Windows.Forms.ViewModels
#endif // UNITTEST

View File

@ -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 {
/// <summary>Unit test for the threaded action class</summary>
[TestFixture]
public class ThreadedActionTest {
#region class DummyContext
/// <summary>Synchronization context that does absolutely nothing</summary>
private class DummyContext : ISynchronizeInvoke {
#region class SimpleAsyncResult
/// <summary>Barebones implementation of an asynchronous result</summary>
private class SimpleAsyncResult : IAsyncResult {
/// <summary>Ehether the asynchronous operation is complete</summary>
/// <remarks>
/// Always true because it completes synchronously
/// </remarks>
public bool IsCompleted { get { return true; } }
/// <summary>
/// Wait handle that can be used to wait for the asynchronous operation
/// </summary>
public WaitHandle AsyncWaitHandle {
get { throw new NotImplementedException("Not implemented"); }
}
/// <summary>Custom state that can be used to pass information around</summary>
public object AsyncState {
get { throw new NotImplementedException("Not implemented"); }
}
/// <summary>Whether the asynchronous operation completed synchronously</summary>
public bool CompletedSynchronously { get { return true; } }
/// <summary>The value returned from the asynchronous operation</summary>
public object ReturnedValue;
}
#endregion // class SimpleAsyncResult
/// <summary>Whether the calling thread needs to use Invoke()</summary>
public bool InvokeRequired {
get { return true; }
}
/// <summary>Schedules the specified method for execution in the target thread</summary>
/// <param name="method">Method the target thread will execute when it is idle</param>
/// <param name="arguments">Arguments that will be passed to the method</param>
/// <returns>
/// An asynchronous result handle that can be used to check on the status of
/// the call and wait for its completion
/// </returns>
public IAsyncResult BeginInvoke(Delegate method, object[] arguments) {
var asyncResult = new SimpleAsyncResult();
asyncResult.ReturnedValue = method.Method.Invoke(method.Target, arguments);
return asyncResult;
}
/// <summary>Waits for the asychronous call to complete</summary>
/// <param name="result">
/// Asynchronous result handle returned by the <see cref="BeginInvoke" /> method
/// </param>
/// <returns>The original result returned by the asychronously called method</returns>
public object EndInvoke(IAsyncResult result) {
return ((SimpleAsyncResult)result).ReturnedValue;
}
/// <summary>
/// Schedules the specified method for execution in the target thread and waits
/// for it to complete
/// </summary>
/// <param name="method">Method that will be executed by the target thread</param>
/// <param name="arguments">Arguments that will be passed to the method</param>
/// <returns>The result returned by the specified method</returns>
public object Invoke(Delegate method, object[] arguments) {
return method.Method.Invoke(method.Target, arguments);
}
}
#endregion // class DummyContext
#region class DummyThreadedAction
/// <summary>Implementation of a threaded action for the unit test</summary>
private class DummyThreadedAction : ThreadedAction {
/// <summary>
/// Initializes a new threaded action, letting the base class figure out the UI thread
/// </summary>
public DummyThreadedAction() : base() {
this.finishedGate = new ManualResetEvent(initialState: false);
}
/// <summary>
/// Initializes a new view model using the specified UI context explicitly
/// </summary>
public DummyThreadedAction(ISynchronizeInvoke uiContext) : base(uiContext) {
this.finishedGate = new ManualResetEvent(initialState: false);
}
/// <summary>Immediately releases all resources owned by the instance</summary>
public override void Dispose() {
base.Dispose();
if(this.finishedGate != null) {
this.finishedGate.Dispose();
this.finishedGate = null;
}
}
/// <summary>Waits until the first background operation is finished</summary>
/// <returns>
/// True if the background operation is finished, false if it is ongoing
/// </returns>
public bool WaitUntilFinished() {
return this.finishedGate.WaitOne(100);
}
/// <summary>Selects the value that will be assigned when the action runs</summary>
/// <param name="valueToAssign">Value the action will assigned when it runs</param>
public void SetValueToAssign(int valueToAssign) {
this.valueToAssign = valueToAssign;
}
/// <summary>Sets up an error the action will fail with when run</summary>
/// <param name="errorToFailWith">Error the action will fail with</param>
public void SetErrorToFailWith(Exception errorToFailWith) {
this.errorToFailWith = errorToFailWith;
}
/// <summary>Last error that was reported by the threaded view model</summary>
public Exception ReportedError {
get { return this.reportedError; }
}
/// <summary>Value that has been assigned from the background thread</summary>
public int AssignedValue {
get { return this.assignedValue; }
}
/// <summary>Executes the threaded action from the background thread</summary>
/// <param name="cancellationToken">Token by which execution can be canceled</param>
protected override void Run(CancellationToken cancellationToken) {
if(this.errorToFailWith != null) {
throw this.errorToFailWith;
}
this.assignedValue = this.valueToAssign;
this.finishedGate.Set();
}
/// <summary>Called when an error occurs in the background thread</summary>
/// <param name="exception">Exception that was thrown in the background thread</param>
protected override void ReportError(Exception exception) {
this.reportedError = exception;
this.finishedGate.Set();
}
/// <summary>Error the action will fail with, if set</summary>
private Exception errorToFailWith;
/// <summary>Value the action will assign to its same-named field</summary>
private int valueToAssign;
/// <summary>Last error that was reported by the threaded view model</summary>
private volatile Exception reportedError;
/// <summary>Triggered when the </summary>
private ManualResetEvent finishedGate;
/// <summary>Value that is assigned through the background thread</summary>
private volatile int assignedValue;
}
#endregion // class DummyThreadedAction
/// <summary>Verifies that the threaded action has a default constructor</summary>
[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();
}
}
}
/// <summary>
/// Verifies that the threaded action can be constructed with a custom UI context
/// </summary>
[Test]
public void HasCustomSychronizationContextConstructor() {
using(new DummyThreadedAction(new DummyContext())) { }
}
/// <summary>Checks that a new threadd action starts out idle and not busy</summary>
[Test]
public void NewInstanceIsNotBusy() {
using(var action = new DummyThreadedAction(new DummyContext())) {
Assert.IsFalse(action.IsBusy);
}
}
/// <summary>
/// Verifies that errors happening in the background processing threads are
/// reported to the main thread
/// </summary>
[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);
}
}
/// <summary>
/// Verifies that the background thread actually executes and can do work
/// </summary>
[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

View File

@ -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 {
/// <summary>Encapsulates an action that can run in a thread</summary>
/// <remarks>
/// <para>
/// 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.
/// </para>
/// <para>
/// 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.
/// </para>
/// </remarks>
public abstract class ThreadedAction : Observable, IDisposable {
#region class ThreadedActionThreadRunner
/// <summary>Thread runner for the threaded action</summary>
private class ThreadedActionThreadRunner : ThreadRunner {
/// <summary>Initializes a new thread runner for the threaded view model</summary>
public ThreadedActionThreadRunner(ThreadedAction viewModel) {
this.threadedAction = viewModel;
}
/// <summary>Reports an error</summary>
/// <param name="exception">Error that will be reported</param>
protected override void ReportError(Exception exception) {
this.threadedAction.reportErrorFromThread(exception);
}
/// <summary>Called when the status of the busy flag changes</summary>
protected override void BusyChanged() {
// Narf. Can't use this.
}
/// <summary>View model the thread runner belongs to</summary>
private ThreadedAction threadedAction;
}
#endregion // class ThreadedActionThreadRunner
/// <summary>Initializes all common fields of the instance</summary>
private ThreadedAction() {
this.callRunIfNotCancelledDelegate = new Action<CancellationTokenSource>(
callThreadedExecuteIfNotCancelled
);
this.reportErrorDelegate = new Action<Exception>(ReportError);
}
/// <summary>Initializes a threaded action that uses its own thread runner</summary>
public ThreadedAction(ISynchronizeInvoke uiContext = null) : this() {
if(uiContext == null) {
this.uiContext = getMainWindow();
} else {
this.uiContext = uiContext;
}
this.ownThreadRunner = new ThreadedActionThreadRunner(this);
}
/// <summary>
/// Initializes a threaded action that uses the view model's thread runner
/// </summary>
/// <param name="viewModel">View model whose thread runner will be used</param>
/// <param name="uiContext">
/// UI dispatcher that can be used to run callbacks in the UI thread
/// </param>
public ThreadedAction(
ThreadedViewModel viewModel, ISynchronizeInvoke uiContext = null
) : this() {
if(uiContext == null) {
this.uiContext = getMainWindow();
} else {
this.uiContext = uiContext;
}
this.externalThreadRunner = viewModel.ThreadRunner;
}
/// <summary>Immediately releases all resources owned by the instance</summary>
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;
}
}
/// <summary>Whether the view model is currently busy executing a task</summary>
public bool IsBusy {
get { return this.isBusy; }
private set {
if(value != this.isBusy) {
this.isBusy = value;
OnPropertyChanged(nameof(IsBusy));
}
}
}
/// <summary>Cancels the running background task, if any</summary>
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;
}
}
}
/// <summary>
/// Starts the task, cancelling the running task before doing so
/// </summary>
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));
}
}
/// <summary>Starts the task</summary>
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));
}
}
/// <summary>Reports an error</summary>
/// <param name="exception">Error that will be reported</param>
protected abstract void ReportError(Exception exception);
/// <summary>Executes the threaded action from the background thread</summary>
/// <param name="cancellationToken">Token by which execution can be canceled</param>
protected abstract void Run(CancellationToken cancellationToken);
/// <summary>
/// Calls the Run() method from the background thread and manages the flags
/// </summary>
/// <param name="cancellationTokenSource"></param>
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));
}
}
}
/// <summary>Schedules one execution of the action</summary>
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
);
}
}
/// <summary>Reports an error that occurred in the runner's background thread</summary>
/// <param name="exception">Exception that the thread has encountered</param>
private void reportErrorFromThread(Exception exception) {
this.uiContext.Invoke(this.reportErrorDelegate, new object[1] { exception });
}
/// <summary>Finds the application's main window</summary>
/// <returns>Main window of the application</returns>
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;
}
}
/// <summary>Synchronization context of the thread in which the view runs</summary>
private ISynchronizeInvoke uiContext;
/// <summary>Delegate for the ReportError() method</summary>
private Action<Exception> reportErrorDelegate;
/// <summary>Delegate for the callThreadedExecuteIfNotCancelled() method</summary>
private Action<CancellationTokenSource> callRunIfNotCancelledDelegate;
/// <summary>Thread runner on which the action can run its background task</summary>
private ThreadedActionThreadRunner ownThreadRunner;
/// <summary>
/// External thread runner on which the action runs its background task if assigned
/// </summary>
private ThreadRunner externalThreadRunner;
/// <summary>Synchronization root for the threaded execute method</summary>
private object runningTaskSyncRoot = new object();
/// <summary>Used to cancel the currently running task</summary>
private CancellationTokenSource currentCancellationTokenSource;
/// <summary>Used to cancel the upcoming task if a re-run was scheduled</summary>
private CancellationTokenSource nextCancellationTokenSource;
/// <summary>Whether the background task is running or waiting to run</summary>
private volatile bool isBusy;
/// <summary>Whether execution is taking place right now</summary>
/// <remarks>
/// If this flag is set and the Start() method is called, another run needs to
/// be scheduled.
/// </remarks>
private bool isRunning;
/// <summary>Whether run was called while the action was already running</summary>
private bool isScheduledAgain;
}
} // namespace Nuclex.Windows.Forms.ViewModels

View File

@ -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; using NUnit.Framework;
@ -148,3 +170,5 @@ namespace Nuclex.Windows.Forms.ViewModels {
} }
} // namespace Nuclex.Windows.Forms.ViewModels } // namespace Nuclex.Windows.Forms.ViewModels
#endif // UNITTEST

View File

@ -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;
using System.ComponentModel; using System.ComponentModel;
@ -135,11 +155,29 @@ namespace Nuclex.Windows.Forms.ViewModels {
RunInBackground(() => throw error); RunInBackground(() => throw error);
} }
/// <summary>
/// Assigns the specified value to the same-named property from a background thread
/// </summary>
/// <param name="value">Value that will be assigned to the same-named property</param>
public void AssignValueInBackgroundThread(int value) {
RunInBackground(
delegate () {
this.assignedValue = value;
this.finishedGate.Set();
}
);
}
/// <summary>Last error that was reported by the threaded view model</summary> /// <summary>Last error that was reported by the threaded view model</summary>
public Exception ReportedError { public Exception ReportedError {
get { return this.reportedError; } get { return this.reportedError; }
} }
/// <summary>Value that has been assigned from the background thread</summary>
public int AssignedValue {
get { return this.assignedValue; }
}
/// <summary>Called when an error occurs in the background thread</summary> /// <summary>Called when an error occurs in the background thread</summary>
/// <param name="exception">Exception that was thrown in the background thread</param> /// <param name="exception">Exception that was thrown in the background thread</param>
protected override void ReportError(Exception exception) { protected override void ReportError(Exception exception) {
@ -148,16 +186,18 @@ namespace Nuclex.Windows.Forms.ViewModels {
} }
/// <summary>Last error that was reported by the threaded view model</summary> /// <summary>Last error that was reported by the threaded view model</summary>
private Exception reportedError; private volatile Exception reportedError;
/// <summary>Triggered when the </summary> /// <summary>Triggered when the </summary>
private ManualResetEvent finishedGate; private ManualResetEvent finishedGate;
/// <summary>Value that is assigned through the background thread</summary>
private volatile int assignedValue;
} }
#endregion // class TestViewModel #endregion // class TestViewModel
/// <summary>Verifies that the threaded view model has a default constructor</summary> /// <summary>Verifies that the threaded view model has a default constructor</summary>
[Test] [Test, Explicit]
public void HasDefaultConstructor() { public void HasDefaultConstructor() {
using(var mainForm = new System.Windows.Forms.Form()) { using(var mainForm = new System.Windows.Forms.Form()) {
mainForm.Show(); mainForm.Show();
@ -201,6 +241,18 @@ namespace Nuclex.Windows.Forms.ViewModels {
} }
} }
/// <summary>
/// Verifies that the background thread actually executes and can do work
/// </summary>
[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 } // namespace Nuclex.Windows.Forms.ViewModels

View File

@ -196,6 +196,12 @@ namespace Nuclex.Windows.Forms.ViewModels {
OnPropertyChanged(nameof(IsBusy)); OnPropertyChanged(nameof(IsBusy));
} }
// For the ThreadedAction class - there should be a better way!
/// <summary>Thread runner that manages the view model's thread</summary>
internal ThreadRunner ThreadRunner {
get { return this.threadRunner; }
}
/// <summary>Reports an error that occurred in the runner's background thread</summary> /// <summary>Reports an error that occurred in the runner's background thread</summary>
/// <param name="exception">Exception that the thread has encountered</param> /// <param name="exception">Exception that the thread has encountered</param>
private void reportErrorFromThread(Exception exception) { private void reportErrorFromThread(Exception exception) {

View File

@ -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 {
/// <summary>Enables consumer to look up the currently active window</summary>
public interface IActiveWindowTracker {
/// <summary>The currently active top-level or modal window</summary>
/// <remarks>
/// If windows live in multiple threads, the property change notification for
/// this property, if supported, might be fired from a different thread.
/// </remarks>
Form ActiveWindow { get; }
}
} // namespace Nuclex.Windows.Forms

View File

@ -36,11 +36,11 @@ namespace Nuclex.Windows.Forms.Views {
this.onViewModelPropertyChangedDelegate = OnViewModelPropertyChanged; this.onViewModelPropertyChangedDelegate = OnViewModelPropertyChanged;
} }
/// <summary>Called when the control's data context is changed</summary> /// <summary>Called when the control's data context is changed</summary>
/// <param name="sender">Control whose data context was changed</param> /// <param name="sender">Control whose data context was changed</param>
/// <param name="oldDataContext">Data context that was previously used</param> /// <param name="oldDataContext">Data context that was previously used</param>
/// <param name="newDataContext">Data context that will be used from now on</param> /// <param name="newDataContext">Data context that will be used from now on</param>
protected virtual void OnDataContextChanged( protected virtual void OnDataContextChanged(
object sender, object oldDataContext, object newDataContext object sender, object oldDataContext, object newDataContext
) { ) {
var oldViewModel = oldDataContext as INotifyPropertyChanged; var oldViewModel = oldDataContext as INotifyPropertyChanged;

View File

@ -36,11 +36,11 @@ namespace Nuclex.Windows.Forms.Views {
this.onViewModelPropertyChangedDelegate = OnViewModelPropertyChanged; this.onViewModelPropertyChangedDelegate = OnViewModelPropertyChanged;
} }
/// <summary>Called when the window's data context is changed</summary> /// <summary>Called when the window's data context is changed</summary>
/// <param name="sender">Window whose data context was changed</param> /// <param name="sender">Window whose data context was changed</param>
/// <param name="oldDataContext">Data context that was previously used</param> /// <param name="oldDataContext">Data context that was previously used</param>
/// <param name="newDataContext">Data context that will be used from now on</param> /// <param name="newDataContext">Data context that will be used from now on</param>
protected virtual void OnDataContextChanged( protected virtual void OnDataContextChanged(
object sender, object oldDataContext, object newDataContext object sender, object oldDataContext, object newDataContext
) { ) {
var oldViewModel = oldDataContext as INotifyPropertyChanged; var oldViewModel = oldDataContext as INotifyPropertyChanged;

View File

@ -0,0 +1,21 @@
using System;
using NUnit.Framework;
namespace Nuclex.Windows.Forms {
/// <summary>Unit test for the window manager</summary>
[TestFixture]
public class WindowManagerTest {
/// <summary>Verifies that the window manager provides a default constructor</summary>
[Test]
public void HasDefaultConstructor() {
Assert.DoesNotThrow(
() => new WindowManager()
);
}
}
} // namespace Nuclex.Windows.Forms