需求:
有一种任务需要定时的执行,而且非常的耗时,因此我把它放到线程池中执行,并设置线程池为1,如果该任务已经在队列中或正在执行该任务,则不要再将该任务加入线程池中了。
测试代码如下
1
using
System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6 using ThreadPool2;
7
8 namespace ThreadPoolTest.MyThreadPool2Test
9 {
10 class Class6
11 {
12 static void Main( string [] args)
13 {
14 MyThreadPool2 pool = new MyThreadPool2( 1 , true , 30000 );
15 object obj = new object ();
16 Random rnd = new Random();
17 for (var i = 0 ; i < 20 ;i ++ )
18 pool.QueueUserWorkItem(call, obj, rnd.Next( 1 , 4 ).ToString(), succ, err);
19 Console.ReadLine();
20 }
21
22 private static void err( object state)
23 {
24 Console.WriteLine( " err
"
);
25 }
26
27 private static void succ( object state, object result)
28 {
29 Console.WriteLine( " succ
"
);
30 }
31
32 private static object call( object state)
33 {
34 while ( true )
35 {
36 Thread.Sleep( 2000 );
37 Console.WriteLine( " exec
"
);
38 }
39 }
40 }
41 }
42
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6 using ThreadPool2;
7
8 namespace ThreadPoolTest.MyThreadPool2Test
9 {
10 class Class6
11 {
12 static void Main( string [] args)
13 {
14 MyThreadPool2 pool = new MyThreadPool2( 1 , true , 30000 );
15 object obj = new object ();
16 Random rnd = new Random();
17 for (var i = 0 ; i < 20 ;i ++ )
18 pool.QueueUserWorkItem(call, obj, rnd.Next( 1 , 4 ).ToString(), succ, err);
19 Console.ReadLine();
20 }
21
22 private static void err( object state)
23 {
24 Console.WriteLine( " err

25 }
26
27 private static void succ( object state, object result)
28 {
29 Console.WriteLine( " succ

30 }
31
32 private static object call( object state)
33 {
34 while ( true )
35 {
36 Thread.Sleep( 2000 );
37 Console.WriteLine( " exec


38 }
39 }
40 }
41 }
42
线程池代码如下,








































































































































































































































































































































































































































本文参考链接:https://www.cnblogs.com/lexus/archive/2008/08/24/1275323.html