/*###################################### # Duck SecurityThread - Version 1 # # Not for release and renaming # # Breakz0ne did coded this, none else # ########################################*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace DuckEmulator.Security { /// /// Status where the Task is on. /// enum ThreadState { Null = 0, Filled = 1, Running = 2, Waiting = 3, Disposed = 4 } class SecurityThread { protected Task fTask; protected ThreadState fState = ThreadState.Null; /// /// State of Task /// internal Boolean Alive { get { return (fTask != null); } } /// /// Needs for collecting /// /// Generation private int Serialize() { return GC.GetGeneration(fTask); } /// /// 3 Types of creating an Thread /// internal SecurityThread() { fTask = null; } internal SecurityThread(Action A) { Parse(A, TaskCreationOptions.None); } internal SecurityThread(Action A, TaskCreationOptions e) { Parse(A, e); } /// /// Initializes the Task /// /// delegate() void /// Addiontionals internal void Parse(Action Action, TaskCreationOptions Opt) { fState = ThreadState.Filled; fTask = new Task(Action, CancellationToken.None, Opt); } /// /// Starts / releases the void(); /// internal void Release() { if (GetState() == ThreadState.Disposed) { return; } if (GetTask().Status == TaskStatus.Running) { Synchronize(); return; } try { GetTask().Start(); } catch ( Exception e ) { throw new SecurityException("SecurityTask could not be started. Errorcode: " + e.Message); } } /// /// Run it smoothly /// internal void Synchronize() { if (!Alive) { return; } GetTask().RunSynchronously(TaskScheduler.FromCurrentSynchronizationContext()); } /// /// Let them wait for * sec /// /// Seconds for waiting internal void Sleep(int Milisec) { if (!Alive) { return; } if (Milisec < 0) { Milisec = 10; } fState = ThreadState.Waiting; GetTask().Wait(Milisec, CancellationToken.None); fState = ThreadState.Running; } internal void WaitForDispose() { if (!Alive) { return; } fState = ThreadState.Waiting; GetTask().Wait(CancellationToken.None); Dispose(); } /// /// Let it keep alive /// internal void KeepAlive() { GC.KeepAlive(GetTask()); } /// /// Optimize /// internal void Optimize() { GC.Collect(Serialize(), GCCollectionMode.Optimized); } /// /// Restore to defaults /// internal void Restore() { GC.Collect(Serialize(), GCCollectionMode.Default); } /// /// Forces the collection /// internal void Force() { GC.Collect(Serialize(), GCCollectionMode.Forced); } /// /// Requests system for final end; /// internal void Finialize() { if (!Alive) { return; } GC.SuppressFinalize(GetTask()); } /// /// Returns the Main-Task where this is runnin' on. /// /// internal Task GetTask() { return this.fTask; } /// /// Returns the State of the Task /// /// internal ThreadState GetState() { return this.fState; } /// /// Dispose main Task /// internal void Dispose() { fTask = null; fState = ThreadState.Disposed; } } }