C#多线程之线程池ThreadPool详解
// TaskInfo contains data that will be passed to the callback method.
public class TaskInfo
{
public RegisteredWaitHandle Handle = null;
public string OtherInfo = "default";
}
public static void Main(string[] args)
{
// 主线程使用AutoResetEvent来给已注册的等待句柄发信号, 此等待句柄执行回调方法
AutoResetEvent ev = new AutoResetEvent(false);
TaskInfo ti = new TaskInfo();
ti.OtherInfo = "First task";
// The TaskInfo for the task includes the registered wait handle returned by RegisterWaitForSingleObject. This
// allows the wait to be terminated when the object has been signaled once (see WaitProc).
ti.Handle = ThreadPool.RegisterWaitForSingleObject(
ev,
new WaitOrTimerCallback(WaitProc),
ti,
1000,
false
);
// 主线程等待三秒,为了演示队列中的线程超时,然后发信号.
Thread.Sleep(3100);
Console.WriteLine("Main thread signals.");
ev.Set();//发信号
// The main thread sleeps, which should give the callback method time to execute. If you comment out this line, the program usually ends before the ThreadPool thread can execute.
Thread.Sleep(1000);
// If you start a thread yourself, you can wait for it to end by calling Thread.Join. This option is not available with thread pool threads.
}
//The callback method executes when the registered wait times out,
//or when the WaitHandle (in this case AutoResetEvent) is signaled.
//WaitProc unregisters the WaitHandle the first time the event is signaled.
public static void WaitProc(object state, bool timedOut)
{
TaskInfo ti = (TaskInfo)state;
string cause = "TIMED OUT";
if (!timedOut) //如果Timeout为false,表示接收到的信号后执行的
{
cause = "SIGNALED";
//如果回调方法执行的话是因为WaitHandle触发信号的话,则用反注册等待句柄来取消回调方法将来的执行。
if (ti.Handle != null)
ti.Handle.Unregister(null);//
}
Console.WriteLine("WaitProc( {0} ) executes on thread {1}; cause = {2}.",
ti.OtherInfo, Thread.CurrentThread.GetHashCode().ToString(), cause);//超时后执行的
}
- .NET Core系列之MemoryCache 初识
- 007手机一键Root(安机网一键Root) v3.0 官方最新版 一键ROOT您的Android手机
- 12306密码被盗了怎么办?12306密码外泄解决方法
- 12个字的qq网名
- 150M迷你型无线路由器怎么设置?
- 192.168.1.1打不开怎么办?路由器192.168.1.1打不开的原因以及解决办法
- 2011年电子报合订本 电子报 编辑部 中文 PDF版 [84M]
- 2015年1月15日小米新旗舰发布会现场图文直播
- 2016.3.1vivo Xplay5新品发布会现场视频直播 优酷直播
- 2016华为P9发布会视频直播地址 4月15日华为P9国行发布会直播