Worker example

This example shows how to create a worker that processes a queue and how to use a worker pool.

using System;
using System.Collections.Generic;
using Energy.Core;

public class QueueWorker : Worker<Queue<string>>
{
    public override void Work()
    {
        while (!Stopped)
        {
            string item = null;
            lock (State)
            {
                if (State.Count > 0)
                    item = State.Dequeue();
            }

            if (item != null)
            {
                Console.WriteLine("Processing: {0}", item);
            }
            else
            {
                Sleep(100);
            }
        }
    }
}

class Program
{
    static void Main()
    {
        Queue<string> queue = new Queue<string>();
        QueueWorker worker = new QueueWorker { State = queue };
        worker.Start();

        for (int i = 0; i < 10; i++)
        {
            lock (queue)
            {
                queue.Enqueue("Item " + i);
            }
        }

        Console.WriteLine("Press any key to stop...");
        Console.ReadKey(true);

        worker.Stop();
        worker.Wait(2.0);
    }
}

See also

  • core-worker