/// <summary> /// 将任务添加到工作线程,在线程池内运行,无法手动结束 /// </summary> /// <param name="worker"></param> /// <param name="callback"></param> public static void AddWork(Action <TaskWorkItem> worker, Action <object> callback) { lock (Instance.enterLock) { var item = new TaskWorkItem() { completed = false, worker = worker }; workItems.Add(item, callback); ThreadPool.QueueUserWorkItem(o => { item.threadId = Thread.CurrentThread.ManagedThreadId; item.worker(item); item.completed = true; }); } }
/// <summary> /// 以异步的方式将任务加入到工作线程,然后在协程中等待任务结束,推荐的使用方式 /// </summary> /// <param name="worker"></param> /// <returns></returns> public static IEnumerator WaitWork(Action <TaskWorkItem> worker) { lock (Instance.enterLock) { var item = new TaskWorkItem() { completed = false, worker = worker }; workItems.Add(item, null); ThreadPool.QueueUserWorkItem(o => { item.threadId = Thread.CurrentThread.ManagedThreadId; item.worker(item); item.completed = true; }); yield return(new WaitUntil(() => item.completed)); } }
/// <summary> /// 将任务添加到工作线程,新建一个线程实例,可以手动结束 /// </summary> /// <param name="worker"></param> /// <param name="callback"></param> /// <returns></returns> public static Thread AddThreadWork(Action <TaskWorkItem> worker, Action <object> callback, ThreadPriority priority = ThreadPriority.Normal) { lock (Instance.enterLock) { var item = new TaskWorkItem() { completed = false, worker = worker }; workItems.Add(item, callback); var thread = new Thread(() => { item.threadId = Thread.CurrentThread.ManagedThreadId; item.worker(item); item.completed = true; }); thread.Priority = priority; thread.Start(); return(thread); } }