.net线程池ThreadPool-1
在.net中Threadpool是一个静态类,继承自object
此类的属性和方法请查看以下链接:
https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.threadpool?view=netframework-4.8
运用到的线程池线程主要有以下几种用法:
当你创建 Task 或 Task<TResult> 对象以异步执行某些任务时,默认情况下,任务计划在线程池线程上运行。 异步计时器使用线程池。 线程池线程执行来自类的回调 System.Threading.Timer 并引发来自类的事件 System.Timers.Timer 。 使用已注册的等待句柄时,系统线程会监视等待句柄的状态。 等待操作完成后,线程池中的工作线程会执行相应的回调函数。 调用 QueueUserWorkItem 方法以将方法排队以便在线程池线程上执行。 为此,可将方法传递给 WaitCallback 委托。 委托具有签名
ThreadPool的常用方法:
1.QueueUserWorkItem(WaitCallback)
其中WaitCallback表示回调委托
WaitCallback委托是不带返回值有一个参数的委托,所以WaitCallback的委托方法必须有一个参数
using System;
using System.Threading;
public class Example
{
public static void Main()
{
// Queue the task.
ThreadPool.QueueUserWorkItem(ThreadProc);
Console.WriteLine("Main thread does some work, then sleeps.");
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
}
// This thread procedure performs the task.
static void ThreadProc(Object stateInfo)
{
// No state object was passed to QueueUserWorkItem, so stateInfo is null.
Console.WriteLine("Hello from the thread pool.");
}
}
// The example displays output like the following:
// Main thread does some work, then sleeps.
// Hello from the thread pool.
// Main thread exits.
2.QueueUserWorkItem(WaitCallback, Object)
其中WaitCallback表示回调委托,Object表示包含回调方法所需的数据对象,对象既可以是一个值
也可以是一个包含特定数据的类的实例
public class Example
{
public static void Main()
{
// Queue the task.
ThreadPool.QueueUserWorkItem(ThreadProc,2);
Console.WriteLine("Main thread does some work, then sleeps.");
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
}
// This thread procedure performs the task.
static void ThreadProc(Object stateInfo)
{
int a = (int)stateInfo
Console.WriteLine("Hello from the thread pool."+a);
}
}
重复就是力量,数量堆死质量

浙公网安备 33010602011771号