细说多线程(六) —— 异步 SqlCommand
目录
一、线程的定义
二、线程的基础知识
三、以ThreadStart方式实现多线程
四、CLR线程池的工作者线程
五、CLR线程池的I/O线程
六、异步 SqlCommand
七、并行编程与PLINQ
八、计时器与锁
六、异步 SqlCommand
从ADO.NET 2.0开始,SqlCommand就新增了几个异步方法执行SQL命令。相对于同步执行方式,它使主线程不需要等待数据库的返回结果,在使用复杂性查询或 批量插入时将有效提高主线程的效率。使用异步SqlCommand的时候,请注意把ConnectionString 的 Asynchronous Processing 设置为 true 。
注意:SqlCommand异步操作的特别之处在于线程并不依赖于CLR线程池,而是由Windows内部提供,这比使用异步委托更有效率。但如果需要使用回调函数的时候,回调函数的线程依然是来自于CLR线程池的工作者线程。
SqlCommand有以下几个方法支持异步操作:
public IAsyncResult BeginExecuteNonQuery (......)
public int EndExecuteNonQuery(IAsyncResult)
public IAsyncResult BeginExecuteReader(......)
public SqlDataReader EndExecuteReader(IAsyncResult)
public IAsyncResult BeginExecuteXmlReader (......)
public XmlReader EndExecuteXmlReader(IAsyncResult)
由于使用方式相似,此处就以 BeginExecuteNonQuery 为例子,介绍一下异步SqlCommand的使用。首先建立connectionString,注意把Asynchronous Processing设置为true来启动异步命令,然后把SqlCommand.CommandText设置为 WAITFOR DELAY "0:0:3" 来虚拟数据库操作。再通过BeginExecuteNonQuery启动异步操作,利用轮询方式监测操作情况。最后在操作完成后使用 EndExecuteNonQuery完成异步操作。
1 class Program 2 { 3 //把Asynchronous Processing设置为true 4 static string connectionString = "Data Source=LESLIE-PC;Initial Catalog=Business;“+ 5 "Integrated Security=True;Asynchronous Processing=true"; 6 7 static void Main(string[] args) 8 { 9 //把CLR线程池最大线程数设置为100010 ThreadPool.SetMaxThreads(1000, 1000); 11 ThreadPoolMessage("Start"); 12 13 //使用WAITFOR DELAY命令来虚拟操作14 SqlConnection connection = new SqlConnection(connectionString); 15 SqlCommand command = new SqlCommand("WAITFOR DELAY '0:0:3';", connection); 16 connection.Open(); 17 18 //启动异步SqlCommand操作,利用轮询方式监测操作19 IAsyncResult result = command.BeginExecuteNonQuery(); 20 ThreadPoolMessage("BeginRead"); 21 while (!result.AsyncWaitHandle.WaitOne(500)) 22 Console.WriteLine("Main thread do work........"); 23 24 //结束异步SqlCommand25 int count= command.EndExecuteNonQuery(result); 26 ThreadPoolMessage("\nCompleted"); 27 Console.ReadKey(); 28 } 29 30 //显示线程池现状31 static void ThreadPoolMessage(string data) 32 { 33 int a, b; 34 ThreadPool.GetAvailableThreads(out a, out b); 35 string message = string.Format("{0}\n CurrentThreadId is {1}\n "+ 36 "WorkerThreads is:{2} CompletionPortThreads is :{3}\n", 37 data, Thread.CurrentThread.ManagedThreadId, a.ToString(), b.ToString()); 38 Console.WriteLine(message); 39 } 40 }
注意运行结果,SqlCommand的异步执行线程并不属于CLR线程池。
如果觉得使用轮询方式过于麻烦,可以使用回调函数,但要注意当调用回调函数时,线程是来自于CLR线程池的工作者线程。
class Program{//把Asynchronous Processing设置为true static string connectionString = "Data Source=LESLIE-PC;Initial Catalog=Business;”+“Integrated Security=True;Asynchronous Processing=true";static void Main(string[] args){//把CLR线程池最大线程数设置为1000 ThreadPool.SetMaxThreads(1000, 1000);ThreadPoolMessage("Start");//使用WAITFOR DELAY命令来虚拟操作 SqlConnection connection = new SqlConnection(connectionString);SqlCommand command = new SqlCommand("WAITFOR DELAY '0:0:3';", connection);connection.Open();//启动异步SqlCommand操作,并把SqlCommand对象传递到回调函数 IAsyncResult result = command.BeginExecuteNonQuery(new AsyncCallback(AsyncCallbackMethod),command);Console.ReadKey();}static void AsyncCallbackMethod(IAsyncResult result){Thread.Sleep(200);ThreadPoolMessage("AsyncCallback");SqlCommand command = (SqlCommand)result.AsyncState;int count=command.EndExecuteNonQuery(result);command.Connection.Close();}//显示线程池现状 static void ThreadPoolMessage(string data){int a, b;ThreadPool.GetAvailableThreads(out a, out b);string message = string.Format("{0}\n CurrentThreadId is {1}\n "+"WorkerThreads is:{2} CompletionPortThreads is :{3}\n",data, Thread.CurrentThread.ManagedThreadId, a.ToString(), b.ToString());Console.WriteLine(message);}}
运行结果:
对JAVA与.NET开发有兴趣的朋友欢迎加入QQ群:162338858
细说多线程(六) —— 异步 SqlCommand相关推荐
- [转]C#综合揭秘——细说多线程(上)
C#综合揭秘--细说多线程(上) 引言 本文主要从线程的基础用法,CLR线程池当中工作者线程与I/O线程的开发,并行操作PLINQ等多个方面介绍多线程的开发. 其中委托的BeginInvoke方法以及 ...
- C#综合揭秘——细说多线程(上)
引言 本文主要从线程的基础用法,CLR线程池当中工作者线程与I/O线程的开发,并行操作PLINQ等多个方面介绍多线程的开发. 其中委托的BeginInvoke方法以及回调函数最为常用. 而 I/O线程 ...
- C#细说多线程(下)
本文主要从线程的基础用法,CLR线程池当中工作者线程与I/O线程的开发,并行操作PLINQ等多个方面介绍多线程的开发. 其中委托的BeginInvoke方法以及回调函数最为常用. 而 I/O线程可能容 ...
- 【C++】多线程与异步编程【四】
文章目录 [C++]多线程与异步编程[四] 0.三问 1.什么是异步编程? 1.1同步与异步 1.2 **阻塞与非阻塞** 2.如何使用异步编程 2.1 使用全局变量与条件变量传递结果 实例1: 2. ...
- C# 多线程六之Task(任务)三之任务工厂
1.知识回顾,简要概述 前面两篇关于Task的随笔,C# 多线程五之Task(任务)一 和 C# 多线程六之Task(任务)二,介绍了关于Task的一些基本的用法,以及一些使用的要点,如果都看懂了,本 ...
- python异步和多线程_Python 异步 IO(asyncio)、多进程、多线程性能对比
IO 密集型应用 IO 密集型应用CPU等待IO时间远大于CPU 自身运行时间,太浪费:常见的 IO 密集型业务包括:浏览器交互.磁盘请求.网络爬虫.数据库请求等 image.png Python 世 ...
- CompletableFuture的多线程和异步监听实现
大家好,我是烤鸭: 今天给大家说的是多线程并发的异步监听的情况. 这里不得不说一下CompletableFuture这个类,普通我们执行多线程的时候只需要另外启动一条线程. 说一下线程的3种方式: e ...
- android分开两个线程做事,android开发教程之handle实现多线程和异步处理
这次浅谈一下Handler,为什么会出现Handler这个功能特性呢?首先,在之前的基本控件,基本都是在Activity的onCreate(Bundle savedInstanceState)方法中调 ...
- springboot主线程_SpringBoot(一) 多线程与异步
多线程与异步 异步是目的,而多线程是实现这个目的的方法. 1 Java J.U.C线程调度 JDK 1.5新增的java.util.concurrent包,增加了并发编程的很多类. Executor ...
最新文章
- ELK教程3:logstash的部署、SpringBoot整合ELK+Filebeat
- MyEclipse扩展功能设置(Eclipse代码提示功能)
- 回归--一个平凡人的2018年总结及2019年展望
- delphi项目开发经验2008年09月18日 星期四 10:07随着项目的失败,这些天一直在总结失败的原因,到底是为什么?
- imx6 休眠 功耗 电流_无线物联网和可穿戴设备的低功耗电源测量挑战
- 关于寻路算法的一些思考(6):预先计算好的路径的所用空间
- 数字图像处理-频率域滤波原理
- squid代理服务器(捎带的SNAT)
- getwayworker timer_Java定时器之Timer学习二
- c语言长整数除法,大整数除法
- github上传_上传本地代码到github
- ajax dorado,02. Dorado的AJAX异常
- mysql列不与第一行的值匹配_MySQL和PHP错误:列数与第1行的值数不匹配
- python菜鸟教程100例-Python 练习实例4
- data transformation python_Data augmentation: 利用python进行图像扩建
- 2014华为机试西安地区B组试题
- Kafka Eagle V1.3.4更新预览
- 【OBS】OBS Studio 视频录制软件 的安装
- 华为性格测评注意事项
- 网站建设网页设计小技巧分享