/// <summary> /// Start or restart the worker thread. /// </summary> public void Start() { lock (mWorkerLock) { /* There is no worker yet, initialize it. */ if (AsyncWorkerTask == null) { AsyncWorkerTask = Task.Factory.StartNew(() => AsyncWorker(CancellationTokenSource.Token, mTaskHandler), CancellationTokenSource.Token); } /* There is a worker already. */ else { /* ReStart worker if it was cancelled. */ if (CancellationTokenSource.IsCancellationRequested) { /* Initialize new thread management stuff. */ CancellationTokenSource = new CancellationTokenSource(); mTaskHandler = new ManualResetEvent(mCommandQueue.Count > 0); /* Wait till last task ends */ try { AsyncWorkerTask.Wait(); } catch (Exception e) { /* Task may already been cancelled. Nothing to do. */ Console.WriteLine(mProducer, "Worker task released already: ", e); } /* Continue with a new worker. */ AsyncWorkerTask = Task.Factory.StartNew(() => AsyncWorker(CancellationTokenSource.Token, mTaskHandler), CancellationTokenSource.Token); } } Console.WriteLine(mProducer, "Command worker started."); } }
/// <summary> /// Stop the worker. /// </summary> public void Stop() { lock (mWorkerLock) { /* Stop worker if it was not already cancelled. */ if (!CancellationTokenSource.IsCancellationRequested) { /* Try to free the task so it can finish if it was waiting. */ try { /* Cancel task. */ CancellationTokenSource.Cancel(); mTaskHandler.Set(); } catch { /* Task handler already disposed so the task is successfully cancelled. Nothing to do. */ } try { /* Wait till the worker finishes its last command. */ AsyncWorkerTask.Wait(); /* Dispose resource. */ mTaskHandler.Dispose(); } catch (Exception e) { /* Task may already been released. Nothing to do. */ Console.WriteLine(mProducer, "Worker task released already: ", e); } } Console.WriteLine(mProducer, "Command worker successfully stopped."); } }