SharpDisplay: Migrating to new robust client scheme.
5 using System.Collections.Generic;
7 using System.Threading;
9 namespace Aga.Controls.Threading
11 public class AbortableThreadPool
13 private LinkedList<WorkItem> _callbacks = new LinkedList<WorkItem>();
14 private Dictionary<WorkItem, Thread> _threads = new Dictionary<WorkItem, Thread>();
16 public WorkItem QueueUserWorkItem(WaitCallback callback)
18 return QueueUserWorkItem(callback, null);
21 public WorkItem QueueUserWorkItem(WaitCallback callback, object state)
23 if (callback == null) throw new ArgumentNullException("callback");
25 WorkItem item = new WorkItem(callback, state, ExecutionContext.Capture());
28 _callbacks.AddLast(item);
30 ThreadPool.QueueUserWorkItem(new WaitCallback(HandleItem));
34 private void HandleItem(object ignored)
41 if (_callbacks.Count > 0)
43 item = _callbacks.First.Value;
44 _callbacks.RemoveFirst();
48 _threads.Add(item, Thread.CurrentThread);
51 ExecutionContext.Run(item.Context,
52 delegate { item.Callback(item.State); }, null);
59 _threads.Remove(item);
64 public bool IsMyThread(Thread thread)
68 foreach (Thread t in _threads.Values)
77 public WorkItemStatus Cancel(WorkItem item, bool allowAbort)
80 throw new ArgumentNullException("item");
83 LinkedListNode<WorkItem> node = _callbacks.Find(item);
86 _callbacks.Remove(node);
87 return WorkItemStatus.Queued;
89 else if (_threads.ContainsKey(item))
93 _threads[item].Abort();
94 _threads.Remove(item);
95 return WorkItemStatus.Aborted;
98 return WorkItemStatus.Executing;
101 return WorkItemStatus.Completed;
105 public void CancelAll(bool allowAbort)
112 foreach (Thread t in _threads.Values)