常用技术

线程池中调用委托
向线程池中放入异步操作
线程池与并行度
实现一个取消选项
线程池中使用等待事件处理器和超时
计时器
BackgroundWorker组件

线程池中的工作线程都是后台线程
保持线程中的操作都是短暂的

异步编程模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
private delegate string RunOnThreadPool(out int threadId);

private static void CallBack(IAsyncResult ar) {
Console.WriteLine("\nstarting a callback ...");
Console.WriteLine("state passed to a callback: {0}", ar.AsyncState);
Console.WriteLine("CallBack is threadpool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
Console.WriteLine("CallBack ThreadPool worker thread id: {0}",
Thread.CurrentThread.ManagedThreadId);
}
private static string Test(out int threadId) {
Console.WriteLine("\nTest Starting ...");
Console.WriteLine("Test is threadpool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(2000);
threadId = Thread.CurrentThread.ManagedThreadId;
return string.Format("Test ThreadPool worker thread id: {0}", threadId);
}

public static void TestPoolDelegate() {
int threadId = 0;
RunOnThreadPool poolDelegate = Test;

Thread t = new Thread(() => Test(out threadId));
t.Start();
t.Join();

Console.WriteLine("TestPoolDelegate ThreadId: {0}", threadId);

// 异步编程模型 APM,推荐使用任务并行库 TPL
IAsyncResult r = poolDelegate.BeginInvoke(out threadId, CallBack, "a delegate asynchronous call");
r.AsyncWaitHandle.WaitOne();
string result = poolDelegate.EndInvoke(out threadId, r);
// *****************************************************

Console.WriteLine("TestPoolDelegate ThreadPool worker thread id: {0}", threadId);
Console.WriteLine(result);

Thread.Sleep(2000);
}

向线程池中放入异步操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
private static void AsyncOperation(object state) {
Console.WriteLine("\n******************************************\n状态: {0}", state ?? "(null)");
Console.WriteLine("Worker thread id: {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
}
public static void TestPoolAsync() {
const int x = 1;
const int y = 2;

const string lambdaState = "state 2";

ThreadPool.QueueUserWorkItem(AsyncOperation, "async state");
Thread.Sleep(1000);

ThreadPool.QueueUserWorkItem(state =>
{
Console.WriteLine("\nOperation state: {0}", state);
Console.WriteLine("Worker Thread id: {0}", Thread.CurrentThread.ManagedThreadId);

Thread.Sleep(5000);
}, "lambda state");

ThreadPool.QueueUserWorkItem(_ =>
{
Console.WriteLine("\nOperation state: {0}, {1}", x + y, lambdaState);
Console.WriteLine("********** Worker Thread id: {0}", Thread.CurrentThread.ManagedThreadId);

Thread.Sleep(10000);
}, "lambda _");

Thread.Sleep(2000);
}