示例#1
0
 /// <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;
         });
     }
 }
示例#2
0
 /// <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));
     }
 }
示例#3
0
        private void Update()
        {
            var items = new TaskWorkItem[workItems.Count];

            workItems.Keys.CopyTo(items, 0);
            for (var i = 0; i < items.Length; i++)
            {
                var key = items[i];
                if (key.completed && workItems.ContainsKey(key))
                {
                    var item = workItems[key];
                    if (item != null)
                    {
                        item.Invoke(key.result);
                    }
                    workItems.Remove(key);
                }
            }
        }
示例#4
0
 /// <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);
     }
 }