dmdb/core/BackgroundProcess.cs

75 lines
2.7 KiB
C#

using System;
using System.Diagnostics;
using System.Threading;
namespace dezentrale.core
{
//! \short Common functionality for complex background behaviours
//! \brief Provides a threading solution for program behaviours that run in
//! background. Also acts as an interface for controlling and
//! presentation code (GUI)
//! \todo Implement cancelling correctly
public abstract class BackgroundProcess
{
//! Target for logging operations performed by the inheriting process classes
public IProcessController LogTarget { get; set; }
//! Can be set by the inheriting class to define whether the GUI shall allow the user to cancel the process
public bool CancelButton { get; protected set; }
//! Textual representation of the process, for displaying
public string Caption { get; protected set; } = "BackgroundProcess";
//! Sub-Steps of the process, to allow the user a better estimation of the duration
public uint Steps { get; protected set; } = 1;
protected abstract bool Run(); //!< Base requirement for inheriting classes: Implement a process. \return if it was successful
private Thread thread = null; //!< Thread instance to be run in background
//! \short Starts an async process run.
//! \return the generated Thread instance, so the application code can watch it too
public Thread StartRun()
{
if (thread != null) return null;
if (LogTarget == null) return null;
thread = new Thread(RunAbstract) { IsBackground = true };
thread.Start();
return thread;
}
//! \internal Helper function for enforcing the ActionCompleted call
private void RunAbstract()
{
LogTarget.ActionCompleted(Run());
}
}
//! \short Example for a BackgroundProcess
//! \brief Implements a threaded solution for logging hello world strings
//! with delays in between them, to simulate background actions
public class HelloWorldProcess : BackgroundProcess
{
public HelloWorldProcess()
{
Caption = "Hello World";
Steps = 20;
}
protected override bool Run()
{
for (uint i = 0; i < 20; i++)
{
string stepName = ((i & 0x01) == 0) ? "Hello" : "World";
LogTarget.StepStarted(i, stepName);
LogTarget.LogLine(stepName, dezentrale.model.LogEvent.ELogLevel.Info, "HelloWorldProcess");
Thread.Sleep(200);
LogTarget.StepCompleted(i, stepName, (i & 0x01) == 0);
Thread.Sleep(200);
}
return true;
}
}
}