自定义队列任务执行器

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Threading.Tasks;
 7 
 8 namespace study01
 9 {
10     /*
11      * 用法:
12       BackTaskListRun.AddFunc(delegate
13                 {
14                     Console.WriteLine("run:"+i);
15                 },null);
16      */
17     /// <summary>
18     /// 后台执行队列
19     /// </summary>
20     public class BackTaskListRun
21     {
22         private static Thread th = null;
23 
24         private class TaskEntity
25         {
26             public TaskEntity(Action<object> func, object data)
27             {
28                 this.Function = func;
29                 this.Data = data;
30             }
31 
32             public Action<object> Function;
33             public object Data;
34         }
35 
36         static Queue<TaskEntity> list = new Queue<TaskEntity>();
37         static BackTaskListRun()
38         {
39             if (th == null)
40             {
41                 th = new Thread(RunTask);
42                 th.IsBackground = true;
43             }
44             if (th.ThreadState != ThreadState.Running)
45             {
46                 th.Start();
47 
48             }
49 
50         }
51 
52         static void RunTask()
53         {
54             while (true)
55             {
56                 if (list.Count == 0)
57                 {
58                     Thread.Sleep(1000);
59                 }
60                 else
61                 {
62                     TaskEntity entity;
63                     lock (list)
64                     {
65                         entity = list.Dequeue();
66                     }
67                     try
68                     {
69                         entity.Function(entity.Data);
70                     }
71                     catch { }
72 
73                 }
74 
75             }
76         }
77         public static void AddFunc(Action<object> func, object data)
78         {
79             lock (list)
80             {
81                 list.Enqueue(new TaskEntity(func, data));
82             }
83         }
84     }
85 }
原文地址:https://www.cnblogs.com/ugvihc/p/11694996.html