c9-01.cs
来自「一本很好的教材.C#开发者必备.内容全面,很难得哦.」· CS 代码 · 共 49 行
CS
49 行
//使用线程池编程示例
using System;
using System.Threading;
public class Sensor
{
static int A = 32;
static String S = "初始化字符串";
public static int Main(string[] args){
AutoResetEvent ev = new AutoResetEvent(false);
ThreadPool.RegisterWaitForSingleObject(
ev,
new WaitOrTimerCallback(WaitThreadFunc),
null,
20000,
false
);
for(int count = 0; count < 5; ++count){
Console.WriteLine("大家好!");
Console.WriteLine("{0}, {1}", A, S);
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadFunc), 5);
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadFunc), 6);
//注册AutoResetEvent事件,该事件建立线程池来调用
//WaitThreadFunc函数.
if (count == 2)
ev.Set();
Thread.Sleep(1000);
}
return 0;
}
public static void ThreadFunc(Object O){
Console.WriteLine("线程池: 工作项目号: {0}, 值: {1}, {2}", O, A, S);
lock(S){
S = "替代字符串";
}
Console.WriteLine("线程池建立完成 {0}", S);
}
public static void WaitThreadFunc(object O, bool signaled){
if (O != null){
Console.WriteLine("****线程池: 等待工作类型: {0}, 值: {1}", O.GetType().Name, S);
}
else
Console.WriteLine("****线程池: 等待工作 值为: {0}", S);
lock(S)
{
S = "等待计时: 特定时间串";
}
Interlocked.Increment(ref A);
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?