Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Threading;
- using System.Drawing;
- namespace SNMediaLib
- {
- public class ImageGeneratorBase
- {
- public int Threads { get; protected set; } = Environment.ProcessorCount;
- Thread[] WorkerThreads;
- Thread MonitorThread;
- Semaphore[] Semaphores;
- public bool Busy { get; set; } = false;
- public int Width { get; protected set; }
- public int Height { get; protected set; }
- BitmapBuffer bitmap;
- public object Parameter;
- public ImageGeneratorBase(int width,int height, int threads)
- {
- this.Width = width;
- this.Height = height;
- this.Threads = threads;
- }
- public ImageGeneratorBase(int width, int height)
- {
- this.Width = width;
- this.Height = height;
- this.Threads = Environment.ProcessorCount;
- }
- public double Progress
- {
- get { return Busy ? (double)((double)finishedLines / (double)bitmap.Height) : 1; }
- }
- int finishedLines = 0;
- int totalLines;
- public event Action<BitmapBuffer> FinishedCallback;
- public event Func<int, int, object, Color> PixelWorker;
- protected virtual Color GetPixelColor(int x,int y, object param)
- {
- if (PixelWorker != null)
- return PixelWorker(x, y, param);
- return Color.Black;
- }
- void Worker(object number)
- {
- int threadNumber = (int)number;
- for (int y = threadNumber; y < bitmap.Height; y += Threads)
- {
- for (int x = 0; x < bitmap.Width; x++)
- {
- bitmap[x, y] = GetPixelColor(x, y, Parameter);
- }
- finishedLines++;
- }
- Semaphores[threadNumber].Release();
- }
- void MonitorWorker()
- {
- WorkerThreads = new Thread[Threads];
- Semaphores = new Semaphore[Threads];
- for (int i = 0; i < Threads; i++)
- {
- Semaphores[i] = new Semaphore(0, 1);
- WorkerThreads[i] = new Thread(new ParameterizedThreadStart(Worker));
- WorkerThreads[i].Start(i);
- }
- for (int i = 0; i < Threads; i++)
- {
- Semaphores[i].WaitOne();
- }
- Busy = false;
- FinishedCallback?.Invoke(bitmap);
- }
- public void Draw(object param)
- {
- Busy = true;
- finishedLines = 0;
- bitmap = new BitmapBuffer(Width, Height);
- MonitorThread = new Thread(MonitorWorker);
- this.Parameter = param;
- Thread mainThread = new Thread(MonitorWorker);
- mainThread.Start();
- }
- public void Abort()
- {
- if(Busy)
- {
- MonitorThread.Abort();
- for (int i=0;i<Threads;i++)
- {
- WorkerThreads[i].Abort();
- Semaphores[i].Dispose();
- }
- WorkerThreads = null;
- Semaphores = null;
- MonitorThread = null;
- bitmap = null;
- Busy = false;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement