QueueUserWorkItem方法将非常简单的任务排入队列

下面这个简单的代码,涉及到资源竞争问题,如果主线程先争取到资源,如果没有等待

一段时间,那么QueueUserWorkItem申请的线程没有机会执行。

  1     using System;
2 using System.Threading;
3
4 public static void Main()
5 {
6 // Queue the task.
7 ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
8
9 Console.WriteLine("Main thread does some work, then sleeps.");
10 // If you comment out the Sleep, the main thread exits before
11 // the thread pool task runs. The thread pool uses background
12 // threads, which do not keep the application running. (This
13 // is a simple example of a race condition.)
14 Thread.Sleep(1000);
15
16 Console.WriteLine("Main thread exits.");
17 }
18
19 // This thread procedure performs the task.
20 static void ThreadProc(Object stateInfo)
21 {
22 // No state object was passed to QueueUserWorkItem, so
23 // stateInfo is null.
24 Console.WriteLine("Hello from the thread pool.");
25 }
26

下面的代码示例使用 QueueUserWorkItem 方法将任务排入队列,并为该任务提供数据。

  1 using System;
2 using System.Threading;
3
4 // TaskInfo holds state information for a task that will be
5 // executed by a ThreadPool thread.
6 public class TaskInfo
7 {
8 // State information for the task. These members
9 // can be implemented as read-only properties, read/write
10 // properties with validation, and so on, as required.
11 public string Boilerplate;
12 public int Value;
13
14 // Public constructor provides an easy way to supply all
15 // the information needed for the task.
16 public TaskInfo(string text, int number)
17 {
18 Boilerplate = text;
19 Value = number;
20 }
21 }
22
23 public class Example
24 {
25 public static void Main()
26 {
27 // Create an object containing the information needed
28 // for the task.
29 TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42);
30
31 // Queue the task and data.
32 if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti))
33 {
34 Console.WriteLine("Main thread does some work, then sleeps.");
35
36 // If you comment out the Sleep, the main thread exits before
37 // the ThreadPool task has a chance to run. ThreadPool uses
38 // background threads, which do not keep the application
39 // running. (This is a simple example of a race condition.)
40 Thread.Sleep(1000);
41
42 Console.WriteLine("Main thread exits.");
43 }
44 else
45 {
46 Console.WriteLine("Unable to queue ThreadPool request.");
47 }
48 }
49
50 // The thread procedure performs the independent task, in this case
51 // formatting and printing a very simple report.
52 //
53 static void ThreadProc(Object stateInfo)
54 {
55 TaskInfo ti = (TaskInfo)stateInfo;
56 Console.WriteLine(ti.Boilerplate, ti.Value);
57 }
58 }
59

使用 RegisterWaitForSingleObject

下面的示例展示多种线程处理功能。

注意:
在Main方法的最后有一句:

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.

  1 using System;
2 using System.Threading;
3
4 // TaskInfo contains data that will be passed to the callback
5 // method.
6 public class TaskInfo
7 {
8 public RegisteredWaitHandle Handle = null;
9 public string OtherInfo = "default";
10 }
11
12 public class Example
13 {
14 public static void Main(string[] args)
15 {
16 // The main thread uses AutoResetEvent to signal the
17 // registered wait handle, which executes the callback
18 // method.
19 AutoResetEvent ev = new AutoResetEvent(false);
20
21 TaskInfo ti = new TaskInfo();
22 ti.OtherInfo = "First task";
23 // The TaskInfo for the task includes the registered wait
24 // handle returned by RegisterWaitForSingleObject. This
25 // allows the wait to be terminated when the object has
26 // been signaled once (see WaitProc).
27 ti.Handle = ThreadPool.RegisterWaitForSingleObject(
28 ev,
29 new WaitOrTimerCallback(WaitProc),
30 ti,
31 1000,
32 false);
33
34 // The main thread waits three seconds, to demonstrate the
35 // time-outs on the queued thread, and then signals.
36 Thread.Sleep(3100);
37 Console.WriteLine("Main thread signals.");
38 ev.Set();
39
40 // The main thread sleeps, which should give the callback
41 // method time to execute. If you comment out this line, the
42 // program usually ends before the ThreadPool thread can execute.
43 Thread.Sleep(1000);
44 // If you start a thread yourself, you can wait for it to end
45 // by calling Thread.Join. This option is not available with
46 // thread pool threads.
47 }
48
49 // The callback method executes when the registered wait times out,
50 // or when the WaitHandle (in this case AutoResetEvent) is signaled.
51 // WaitProc unregisters the WaitHandle the first time the event is
52 // signaled.
53 public static void WaitProc(object state, bool timedOut)
54 {
55 // The state object must be cast to the correct type, because the
56 // signature of the WaitOrTimerCallback delegate specifies type
57 // Object.
58 TaskInfo ti = (TaskInfo)state;
59
60 string cause = "TIMED OUT";
61 if (!timedOut)
62 {
63 cause = "SIGNALED";
64 // If the callback method executes because the WaitHandle is
65 // signaled, stop future execution of the callback method
66 // by unregistering the WaitHandle.
67 if (ti.Handle != null)
68 ti.Handle.Unregister(null);
69 }
70
71 Console.WriteLine("WaitProc( {0} ) executes on thread {1}; cause = {2}.",
72 ti.OtherInfo,
73 Thread.CurrentThread.GetHashCode().ToString(),
74 cause
75 );
76 }
77 }
78

.NET并行计算和并发8-QueueUserWorkItem异步的更多相关文章

  1. C#并发编程之异步编程2

    C#并发编程之异步编程(二)   写在前面 前面一篇文章介绍了异步编程的基本内容,同时也简要说明了async和await的一些用法.本篇文章将对async和await这两个关键字进行深入探讨,研究其中 ...

  2. .NET并行计算和并发7-Task异步

    使用任务并行库执行异步任务 下面的示例演示如何通过调用 TaskFactory.StartNew 方法来创建并使用 Task 对象. using System; using System.Thread ...

  3. 关于如何提高Web服务端并发效率的异步编程技术

    最近我研究技术的一个重点是java的多线程开发,在我早期学习java的时候,很多书上把java的多线程开发标榜为简单易用,这个简单易用是以C语言作为参照的,不过我也没有使用过C语言开发过多线程,我只知 ...

  4. 浅入了解GCD 并发 并行 同步 异步 多线程

     什么是 GCD?! GCD就是一个函数库(废话) 用来压榨系统的资源,解决多线程处理中一些问题的库(知道这个就够了,很多电影角色都是因为知道太多死得很惨!!!!!) 1.并发与并行 Concurre ...

  5. 如何提高Web服务端并发效率的异步编程技术

    作为一名web工程师都希望自己做的web应用能被越来越多的人使用,如果我们所做的web应用随着用户的增多而宕机了,那么越来越多的人就会变得越来越少了,为了让我们的web应用能有更多人使用,我们就得提升 ...

  6. 理论铺垫:阻塞IO、非阻塞IO、IO多路复用/事件驱动IO(单线程高并发原理)、异步IO

    完全来自:http://www.cnblogs.com/alex3714/articles/5876749.html 同步IO和异步IO,阻塞IO和非阻塞IO分别是什么,到底有什么区别?不同的人在不同 ...

  7. 串行&并行&并发,同步&异步

    1. 串行&并行&并发 1.1 串行 这个非常好理解,字面意思,像串成一个串一样,顺序执行 上一个没执行完的话,后面的就必须无条件等待 一般情况就是一个线程里:任务一个接一个执行,类似 ...

  8. 操作系统的发展史(并发与并行)<异步与同步>《进程与程序》[非堵塞与堵塞]

    目录 一:一:手工操作 -- 穿孔卡片 1.简介 二:手工操作方式两个特点: 三:批处理 -- 磁带存储 1.联机批处理系统 2.脱机批处理系统 3.多道程序系统 4.多道批处理系统 四:总结发展史 ...

  9. C#并发编程-2 异步编程基础-Task

    一 异步延迟 在异步方法中,如果需要让程序延迟等待一会后,继续往下执行,应使用Task.Delay()方法. //创建一个在指定的毫秒数后完成的任务. public static Task Delay ...

随机推荐

  1. 11个简单的Java性能调优技巧,傻瓜都能学会!

    大多数开发人员理所当然地以为性能优化很复杂,需要大量的经验和知识.好吧,不能说这是完全错误的.优化应用程序以获得最佳性能不是一件容易的事情.但是,这并不意味着如果你不具备这些知识,就不能做任何事情. ...

  2. 自制操作系统Antz(4)——进入保护模式 (下) 实现内核并从硬盘载入

    Antz系统更新地址: https://www.cnblogs.com/LexMoon/category/1262287.html Linux内核源码分析地址:https://www.cnblogs. ...

  3. SpringBoot整合shiro实现用户的认证授权

    * 项目环境搭建 * 配置ShiroConfig,用于shiro的基本配置和注入自定义规则 * 实现自定义的realm,继承AuthorizingRealm * 编写测试controller和页面 基 ...

  4. 复旦大学2017--2018学年第一学期高等代数I期末考试情况分析

    一.期末考试成绩班级前十名 郭宇城(100).魏一鸣(93).乔嘉玮(92).刘宇其(90).朱柏青(90).王成文健(90).方博越(88).熊子恺(88).张君格(88).崔镇涛(87).史书珣( ...

  5. jQuery实现淘宝轮播图

    我爱撸码,撸码使我感到快乐大家好,我是Counter今天给大家分享的是利用jQuery来实现淘宝轮播图,揭开这层神秘的面纱,CSS样式就不做过多的赘述了,主要就是实现的原理,也就是jQuery,老样子 ...

  6. UVA11997 K Smallest Sums

    思路 经典的k路归并问题 问题先转换为2路的有序表归并 先让A[1~k]都和B[1]相加,然后加入堆中,取出堆顶(A[x]+B[y])之后,再放入A[x]+B[y+1] 代码 #include < ...

  7. 在新获取git中项目时出现的问题汇总

    新下拉git项目,今天遇到的问题,因为刚配置实用jdk和idea,所以有可能在打开springboot项目时查看mysql数据库驱动显示为红色. 之后看到pom文件也没有错,最后发现才是在项目中还没有 ...

  8. 【NET Core】事务TransactionScope

    .NET FrameWork时期: TransactionScope是FCL System.Transactions命名空间下的分布式事务组件,它默认为本地事务,当系统有需要时可以自动提升为分布式事务 ...

  9. BZOJ 2423 (求LCS的长度和种类数)

    Description 字符序列的子序列是指从给定字符序列中随意地(不一定连续)去掉若干个字符(可能一个也不去掉)后所形成的字符序列.令给定的字符序列X=“x0,x1,…,xm-1”,序列Y=“y0, ...

  10. CentOs系统设置python版本

    一.针对当前终端生效 最近云服务器安装了centos7系统,python默认版本是2.7.5,但是习惯用anaconda3, 安装anaconda3之后将系统默认python版本更改为python3. ...