using System.ComponentModel;
using System.Threading;
namespace RuriLib.Runner
{
///
/// Whether the AbortableBackgroundWorker is idle, stopping or working.
///
public enum WorkerStatus
{
/// The Worker is not working.
Idle,
/// The Worker is working.
Running,
/// The Worker is cancelling its work.
Stopping
}
///
/// A Worker that can be aborted like normal threads.
///
public class AbortableBackgroundWorker : BackgroundWorker
{
private Thread workerThread;
/// The Status of the Worker.
public WorkerStatus Status { get; set; }
/// The Id of the Worker.
public int Id { get; set; }
///
/// OnDoWork that supports aborting.
///
/// The DoWorkEventArgs
protected override void OnDoWork(DoWorkEventArgs e)
{
workerThread = Thread.CurrentThread;
try
{
base.OnDoWork(e);
}
catch (ThreadAbortException)
{
e.Cancel = true; //We must set Cancel property to true!
Thread.ResetAbort(); //Prevents ThreadAbortException propagation
}
}
/// Calls the Abort() method on the inner Thread.
public void Abort()
{
if (workerThread != null)
{
workerThread.Abort();
workerThread = null;
}
}
}
}