转:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.threadpool.queueuserworkitem?view=netframework-4.7.2

Queues a method for execution. The method executes when a thread pool thread becomes available.

重载

QueueUserWorkItem(WaitCallback)

Queues a method for execution. The method executes when a thread pool thread becomes available.

QueueUserWorkItem(WaitCallback, Object)

Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.

QueueUserWorkItem(WaitCallback)

Queues a method for execution. The method executes when a thread pool thread becomes available.

C#复制

public static bool QueueUserWorkItem (System.Threading.WaitCallback callBack);

参数

callBack

WaitCallback

A WaitCallback that represents the method to be executed.

返回

Boolean

true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.

异常

ArgumentNullException

callBack is null.

NotSupportedException

The common language runtime (CLR) is hosted, and the host does not support this action.

示例

The following example uses the QueueUserWorkItem(WaitCallback) method overload to queue a task, which is represented by the ThreadProc method, to execute when a thread becomes available. No task information is supplied with this overload. Therefore, the information that is available to the ThreadProc method is limited to the object the method belongs to.

C#复制

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.

注解

You can place data required by the queued method in the instance fields of the class in which the method is defined, or you can use the QueueUserWorkItem(WaitCallback, Object) overload that accepts an object containing the necessary data.

备注

Visual Basic users can omit the WaitCallback constructor, and simply use the AddressOf operator when passing the callback method to QueueUserWorkItem.Visual Basic automatically calls the correct delegate constructor.

Version Information

In the .NET Framework version 2.0, the Thread.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method. In earlier versions, the principal information is not propagated.

另请参阅

托管线程池The Managed Thread Pool

QueueUserWorkItem(WaitCallback, Object)

Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.

C#复制

public static bool QueueUserWorkItem (System.Threading.WaitCallback callBack, object state);

参数

callBack

WaitCallback

A WaitCallback representing the method to execute.

state

Object

An object containing data to be used by the method.

返回

Boolean

true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.

异常

NotSupportedException

The common language runtime (CLR) is hosted, and the host does not support this action.

ArgumentNullException

callBack is null.

示例

The following example uses the .NET thread pool to calculate the Fibonacci result for five numbers between 20 and 40. Each Fibonacci result is represented by the Fibonacciclass, which provides a method named ThreadPoolCallback that performs the calculation.An object that represents each Fibonacci value is created, and the ThreadPoolCallbackmethod is passed to QueueUserWorkItem, which assigns an available thread in the pool to execute the method.

Because each Fibonacci object is given a semi-random value to compute, and because each thread will be competing for processor time, you cannot know in advance how long it will take for all five results to be calculated. That is why each Fibonacci object is passed an instance of the ManualResetEvent class during construction. Each object signals the provided event object when its calculation is complete, which allows the primary thread to block execution with WaitAll until all five Fibonacci objects have calculated a result. The Main method then displays each Fibonacci result.

C#复制

using System;
using System.Threading;public class Fibonacci
{private ManualResetEvent _doneEvent;public Fibonacci(int n, ManualResetEvent doneEvent){N = n;_doneEvent = doneEvent;}public int N { get; }public int FibOfN { get; private set; }public void ThreadPoolCallback(Object threadContext){int threadIndex = (int)threadContext;Console.WriteLine($"Thread {threadIndex} started...");FibOfN = Calculate(N);Console.WriteLine($"Thread {threadIndex} result calculated...");_doneEvent.Set();}public int Calculate(int n){if (n <= 1){return n;}return Calculate(n - 1) + Calculate(n - 2);}
}public class ThreadPoolExample
{static void Main(){const int FibonacciCalculations = 5;var doneEvents = new ManualResetEvent[FibonacciCalculations];var fibArray = new Fibonacci[FibonacciCalculations];var rand = new Random();Console.WriteLine($"Launching {FibonacciCalculations} tasks...");for (int i = 0; i < FibonacciCalculations; i++){doneEvents[i] = new ManualResetEvent(false);var f = new Fibonacci(rand.Next(20, 40), doneEvents[i]);fibArray[i] = f;ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);}WaitHandle.WaitAll(doneEvents);Console.WriteLine("All calculations are complete.");for (int i = 0; i < FibonacciCalculations; i++){Fibonacci f = fibArray[i];Console.WriteLine($"Fibonacci({f.N}) = {f.FibOfN}");}}
}
// The output is similar to:
// Launching 5 tasks...
// Thread 3 started...
// Thread 4 started...
// Thread 2 started...
// Thread 1 started...
// Thread 0 started...
// Thread 2 result calculated...
// Thread 3 result calculated...
// Thread 4 result calculated...
// Thread 1 result calculated...
// Thread 0 result calculated...
// All calculations are complete.
// Fibonacci(35) = 9227465
// Fibonacci(27) = 196418
// Fibonacci(25) = 75025
// Fibonacci(25) = 75025
// Fibonacci(27) = 196418

注解

If the callback method requires complex data, you can define a class to contain the data.

备注

Visual Basic users can omit the WaitCallback constructor, and simply use the AddressOf operator when passing the callback method to QueueUserWorkItem.Visual Basic automatically calls the correct delegate constructor.

Version Information

In the .NET Framework version 2.0, the Thread.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method. In earlier versions, the principal information is not propagated.

另请参阅

托管线程池The Managed Thread Pool

QueueUserWorkItem(WaitCallback, Object)相关推荐

  1. C#多线程学习(四) 多线程的自动管理(线程池) (转载系列)——继续搜索引擎研究...

    在多线程的程序中,经常会出现两种情况: 一种情况:   应用程序中,线程把大部分的时间花费在等待状态,等待某个事件发生,然后才能给予响应                   这一般使用ThreadPo ...

  2. C# 多线程学习总结

    C#多线程学习(一) 多线程的相关概念 什么是进程? 当一个程序开始运行时,它就是一个进程,进程包括运行中的程序和程序所使用到的内存和系统资源.而一个进程又是由多个线程所组成的. 什么是线程? 线程是 ...

  3. [转]C#多线程学习(四) 多线程的自动管理(线程池)

    在多线程的程序中,经常会出现两种情况: 一种情况:   应用程序中,线程把大部分的时间花费在等待状态,等待某个事件发生,然后才能给予响应                   这一般使用ThreadPo ...

  4. [转]C#综合揭秘——细说多线程(上)

    C#综合揭秘--细说多线程(上) 引言 本文主要从线程的基础用法,CLR线程池当中工作者线程与I/O线程的开发,并行操作PLINQ等多个方面介绍多线程的开发. 其中委托的BeginInvoke方法以及 ...

  5. C#的多线程(2)——机制探索

    注:本文中出现的代码均在.net Framework RC3环境中运行通过 一.多线程的概念 Windows是一个多任务的系统,如果你使用的是windows 2000及 其以上版本,你可以通过任务管理 ...

  6. C#综合揭秘——细说多线程(上)

    引言 本文主要从线程的基础用法,CLR线程池当中工作者线程与I/O线程的开发,并行操作PLINQ等多个方面介绍多线程的开发. 其中委托的BeginInvoke方法以及回调函数最为常用. 而 I/O线程 ...

  7. C# 线程池ThreadPool

    什么是线程池?为什么要用线程池?怎么用线程池? 1. 什么是线程池? .NET Framework的ThreadPool类提供一个线程池,该线程池可用于执行任务.发送工作项.处理异步 I/O.代表其他 ...

  8. C#的多线程机制探索7

    大家可以看到,在上面的例程中,同步是通过等待Monitor.Pulse()来完成的.首先生产者生产了一个值,而同一时刻消费者处于等待状态,直到收到生产者的"脉冲(Pulse)"通知 ...

  9. 线程池和定时器——多线程的自动管理(转载)

    ---来自选择自 AloneSword 的 Blog 在多线程的程序中,经常会出现两种情况.一种情况下,应用程序中的线程把大部分的时间花费在等待状态,等待某个事件发生,然后才能给予响应:而另外一种情况 ...

最新文章

  1. iOS 高德导航按返回后报错 解决
  2. hdu-5778 abs(暴力枚举)
  3. 【码书】一本经典且内容全面算法书籍,学算法必备
  4. ArcGIS Engine控件运行许可学习总结
  5. 动态规划(斜率优化):BZOJ 3675 [Apio2014]序列分割
  6. mount 挂载光盘
  7. C++编译运行过程分析
  8. Qt工作笔记-动态曲线图
  9. (组合数学习题)递推关系一道经典题分析与解答
  10. 爬虫python名词解释_python爬虫
  11. 转:python的内置对象
  12. 数据结构思维 翻译完成
  13. 杰出企业家的20个好习惯
  14. 修复office安装提示1706
  15. Android——实时显示系统时间
  16. 《先知·逸乐》| 《先知·自由》
  17. 用户计算机名更改为英文,win10将用户名改为英文怎么改_win10如何更改用户名为英文图文教程-系统城...
  18. flask (python web app framework)
  19. python如何更新包_python如何更新包
  20. 如何防止uniswap/pancakeswap被机器人夹

热门文章

  1. linux wifi名称设置中文乱码,无线wifi名称怎样能设置中文而且不乱码
  2. android wifi tcpip,Android无线调试:tcpip无线连接 | WiFi apk无线连接
  3. 解密:Jersey 入门指南系列1
  4. 选择法排序对数组进行升序
  5. 腾讯员工平均年薪近百万,工程师一个月赚8万!网友:我和马云财产加起来过千亿,我骄傲了嘛?...
  6. 三流大学毕业的我,如何一年内进入大公司
  7. Android播放无声音,Android呼叫Mediaplayer播放无声音频
  8. 《细胞》重磅连发:记忆可“遗传”!
  9. 利用docker搭建php7cms靶机
  10. Apple Developer 注册及DUNS编码申请