Threading and workers
The Energy.Core namespace provides a lightweight worker and thread-pool framework.
Worker
Energy.Core.WorkerWork() method to implement your own long-running logic.
public class ClockWorker : Energy.Core.Worker<object>
{
public override void Work()
{
while (!Stopped)
{
Console.WriteLine(DateTime.Now);
Sleep(1000);
}
}
}
ClockWorker worker = new ClockWorker();
worker.Start();
// do something else...
worker.Stop();
worker.Wait(5000);
Properties
| Property | Description |
|---|---|
Running |
True while the worker thread is alive. |
Stopped |
Stopped state. Set to true to ask the worker to finish. |
Background |
Whether the worker runs as a background thread. |
State |
User-defined state object. |
LastStart |
Time when the worker was last started. |
CurrentCulture |
Culture used by the worker thread. |
StoppedResetEvent |
ManualResetEvent signaled when the worker stops. |
Methods
| Method | Description |
|---|---|
Work() |
Override this method with the worker logic. |
Start() |
Start the worker thread. |
Stop() |
Set Stopped to true. |
Wait(int time) |
Wait up to the specified number of milliseconds for the thread to exit. |
Wait(double time) |
Wait up to the specified number of seconds. |
Abort() |
Abort the thread. |
Sleep() |
Sleep until woken. |
Sleep(int time) |
Sleep for the specified number of milliseconds. |
Sleep(double time) |
Sleep for the specified number of seconds. |
Worker
Energy.Core.Worker is a static helper class containing utility methods and the pool implementation.
Pool
Energy.Core.Worker.Pool
Energy.Core.Worker.Pool<string> pool = new Energy.Core.Worker.Pool<string>();
pool.Add("first");
pool.Add("second");
pool.Spawn();
pool.Start();
// ...
pool.Stop();
Pool
Energy.Core.Worker.Pool is a non-generic pool of object.
Utility methods
| Method | Description |
|---|---|
Worker.Wait(Thread, int) |
Wait for a thread to exit. |
Worker.Fire(Action) |
Start a thread that executes a delegate. |
Worker.Fire(string, Action) |
Start a named thread. |
Worker.RemoveUnused(object[], Action<object>) |
Remove stopped workers from an array. |
Worker.StopRunning(object[], Action<object>) |
Stop all workers in an array. |
Example
using System;
using Energy.Core;
public class NumberWorker : Worker<int>
{
public override void Work()
{
while (!Stopped)
{
Console.WriteLine(State++);
Sleep(500);
}
}
}
class Program
{
static void Main()
{
NumberWorker worker = new NumberWorker { State = 0 };
worker.Start();
Console.ReadKey(true);
worker.Stop();
worker.Wait(3.0);
}
}