C#中处理耗时任务的几种方式
0、准备
首先,我们先创建几个耗时任务:
public class TestTasks
{
//无参、无返回值任务
public void Task1()
{
Console.WriteLine("task1.");
Thread.Sleep(5000);
Console.WriteLine("task1 completed.");
}
//有参数、无返回值任务
public void Task2(int x)
{
if (x < 2000)
{
x += 2000;
}
Console.WriteLine("task2.");
Thread.Sleep(x);
Console.WriteLine("task2 completed.");
}
//有参数,有返回值任务
public int Task3(int x)
{
if (x < 2000)
{
x += 2000;
}
Console.WriteLine("task3.");
Thread.Sleep(x);
Console.WriteLine("task3 completed.");
return x;
}
}
1、创建新线程执行方法
var tt = new TestTasks();
new Thread(tt.Task1).Start();
//针对有参数的任务,需要用Lambda进行包装或者使用ParameterizedThreadStart对象
new Thread(x=>tt.Task2((int)x)).Start((object)1000);
//使用ParameterizedThreadStart,要求要执行的方法参数必须为object,同时无返回值。
//new Thread(new ParameterizedThreadStart(tt.Task2)).Start((object)1000);
注意:使用该方式无法执行带返回值的方法。
推荐指数:★★
2、使用异步调用方式执行方法
var tt = new TestTasks();
Action ac = tt.Task1;
Action<int> ac2 = tt.Task2;
ac.BeginInvoke(null, null);
ac2.BeginInvoke(1000, null, null);
//以下是调用有参数,有返回值的方法
//代码一
private delegate int AsyncCaller(int x); //该代码放在方法体外部
AsyncCaller ac = new AsyncCaller(tt.Task3);
var asyncResult = ac.BeginInvoke(1000,null,null);
int result = ac.EndInvoke(asyncResult); //接收返回值
//代码二,使用Func简化代码
Func<int,int> ac = tt.Task3;
var asyncResult = ac.BeginInvoke(1000,null,null);
int result = ac.EndInvoke(asyncResult);
注意:通过这种方式生成新线程是运行在后台的(background),优先级为normal
推荐指数:★★
3、通过ThreadPool(线程池)执行方法
var tt = new TestTasks();
ThreadPool.QueueUserWorkItem(o => tt.Task1());
ThreadPool.QueueUserWorkItem(o => tt.Task2(1000));
注意:该方式不支持返回值,可以将返回值保存在引入类型的参数上,然后进行迂回实现
推荐指数:★★★
4、通过BackgroundWorker(后台Worker)执行方法
var tt = new TestTasks();
var bw = new BackgroundWorker();
bw.DoWork += (sender, e) => tt.Task1();
bw.DoWork += (sender, e) => tt.Task2(1000);
//要接收返回值,必须将返回值赋值给Result。
bw.DoWork += (sender, e) => e.Result = tt.Task3(1000);
bw.RunWorkerAsync();
//注册事件使用返回值
bw.RunWorkerCompleted += (sender, e) => Console.WriteLine(e.Result);
注意:使用BackgroundWorker注册DoWork事件的任务只能挨个执行,如果要同时执行多个任务,需要多个BackgroundWorker。要使用返回值,一定要记得赋值给Result。
推荐指数:★★
5、同时Task执行方法
var tt = new TestTasks();
var t1 = Task.Factory.StartNew(tt.Task1);
var t2 = Task.Factory.StartNew(() => tt.Task2(1000));
var t3 =Task.Factory.StartNew(() => tt.Task3(1000));
//等待t1,t2,t3执行完成
Task.WaitAll(t1,t2,t3);
Console.WriteLine(t3.Result);
注意:Task具有灵活的控制能力,同时可以单个等待,多个等待。
推荐指数:★★★★★
6、使用async/await执行方法
private async void AsyncRunTask()
{
var tt = new TestTasks();
await Task.Factory.StartNew(tt.Task1);
await Task.Factory.StartNew(() => tt.Task2(1000));
var result = await Task.Factory.StartNew(() => tt.Task3(1000));
Console.WriteLine(result);
}
AsyncRunTask();
Console.WriteLine("不用等待,我先执行了。");
注意:需要Framework4.5的支持
推荐指数:★★★★
The End
没有原理,没有言语,相信以大家聪明的大脑,已经学会如何在C#中执行耗时任务和使用多线程了。
*:first-child {
margin-top: 0 !important;
}
body>*:last-child {
margin-bottom: 0 !important;
}
/* BLOCKS
=============================================================================*/
p, blockquote, ul, ol, dl, table, pre {
margin: 15px 0;
}
/* HEADERS
=============================================================================*/
h1, h2, h3, h4, h5, h6 {
margin: 20px 0 10px;
padding: 0;
font-weight: bold;
-webkit-font-smoothing: antialiased;
}
h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code {
font-size: inherit;
}
h1 {
font-size: 28px;
color: #000;
}
h2 {
font-size: 24px;
border-bottom: 1px solid #ccc;
color: #000;
}
h3 {
font-size: 18px;
}
h4 {
font-size: 16px;
}
h5 {
font-size: 14px;
}
h6 {
color: #777;
font-size: 14px;
}
body>h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child {
margin-top: 0;
padding-top: 0;
}
a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 {
margin-top: 0;
padding-top: 0;
}
h1+p, h2+p, h3+p, h4+p, h5+p, h6+p {
margin-top: 10px;
}
/* LINKS
=============================================================================*/
a {
color: #4183C4;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* LISTS
=============================================================================*/
ul, ol {
padding-left: 30px;
}
ul li > :first-child,
ol li > :first-child,
ul li ul:first-of-type,
ol li ol:first-of-type,
ul li ol:first-of-type,
ol li ul:first-of-type {
margin-top: 0px;
}
ul ul, ul ol, ol ol, ol ul {
margin-bottom: 0;
}
dl {
padding: 0;
}
dl dt {
font-size: 14px;
font-weight: bold;
font-style: italic;
padding: 0;
margin: 15px 0 5px;
}
dl dt:first-child {
padding: 0;
}
dl dt>:first-child {
margin-top: 0px;
}
dl dt>:last-child {
margin-bottom: 0px;
}
dl dd {
margin: 0 0 15px;
padding: 0 15px;
}
dl dd>:first-child {
margin-top: 0px;
}
dl dd>:last-child {
margin-bottom: 0px;
}
/* CODE
=============================================================================*/
pre, code, tt {
font-size: 12px;
font-family: Consolas, "Liberation Mono", Courier, monospace;
}
code, tt {
margin: 0 0px;
padding: 0px 0px;
white-space: nowrap;
border: 1px solid #eaeaea;
background-color: #f8f8f8;
border-radius: 3px;
}
pre>code {
margin: 0;
padding: 0;
white-space: pre;
border: none;
background: transparent;
}
pre {
background-color: #f8f8f8;
border: 1px solid #ccc;
font-size: 13px;
line-height: 19px;
overflow: auto;
padding: 6px 10px;
border-radius: 3px;
}
pre code, pre tt {
background-color: transparent;
border: none;
}
kbd {
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background-color: #DDDDDD;
background-image: linear-gradient(#F1F1F1, #DDDDDD);
background-repeat: repeat-x;
border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD;
border-image: none;
border-radius: 2px 2px 2px 2px;
border-style: solid;
border-width: 1px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
line-height: 10px;
padding: 1px 4px;
}
/* QUOTES
=============================================================================*/
blockquote {
border-left: 4px solid #DDD;
padding: 0 15px;
color: #777;
}
blockquote>:first-child {
margin-top: 0px;
}
blockquote>:last-child {
margin-bottom: 0px;
}
/* HORIZONTAL RULES
=============================================================================*/
hr {
clear: both;
margin: 15px 0;
height: 0px;
overflow: hidden;
border: none;
background: transparent;
border-bottom: 4px solid #ddd;
padding: 0;
}
/* IMAGES
=============================================================================*/
img {
max-width: 100%
}
-->
C#中处理耗时任务的几种方式的更多相关文章
- c#ASP.NET中页面传值共有这么几种方式
一.目前在ASP.NET中页面传值共有这么几种方式: 1.Response.Redirect("http://www.hao123.com",false); 目标页面和原页面可以在 ...
- strus2中获取表单数据 两种方式 属性驱动 和模型驱动
strus2中获取表单数据 两种方式 属性驱动 和模型驱动 属性驱动 /** * 当前请求的action在栈顶,ss是栈顶的元素,所以可以利用setValue方法赋值 * 如果一个属性在对象栈,在页面 ...
- 怎样在Android开发中FPS游戏实现的两种方式比较
怎样在Android开发中FPS游戏实现的两种方式比较 如何用Android平台开发FPS游戏,其实现过程有哪些方法,这些方法又有哪些不同的地方呢?首先让我们先了解下什么是FPS 英文名:FPS (F ...
- Struts2中访问web元素的四种方式
Struts2中访问web元素的四种方式如下: 通过ActionContext来访问Map类型的request.session.application对象. 通过实现RequestAware.Sess ...
- HTML中设置背景图的两种方式
HTML中设置背景图的两种方式 1.background background:url(images/search.png) no-repeat top; 2.background-image ...
- [Android] Android ViewPager 中加载 Fragment的两种方式 方式(二)
接上文: https://www.cnblogs.com/wukong1688/p/10693338.html Android ViewPager 中加载 Fragmenet的两种方式 方式(一) 二 ...
- [Android] Android ViewPager 中加载 Fragment的两种方式 方式(一)
Android ViewPager 中加载 Fragmenet的两种方式 一.当fragment里面的内容较少时,直接 使用fragment xml布局文件填充 文件总数 布局文件:view_one. ...
- .Net 中读写Oracle数据库常用两种方式
.net中连接Oracle 的两种方式:OracleClient,OleDb转载 2015年04月24日 00:00:24 10820.Net 中读写Oracle数据库常用两种方式:OracleCli ...
- 在Tomcat中部署web项目的三种方式
搬瓦工搭建SS教程 SSR免费节点:http://www.xiaokeli.me 在这里介绍在Tomcat中部署web项目的三种方式: 1.部署解包的webapp目录 2.打包的war文件 3.Man ...
随机推荐
- 理解与模拟一个简单servlet容器
servlet接口 使用servlet编程需要实现或者继承实现了javax.servlet.Servlet接口的类,其中定义了5个签名方法: public void init(ServletConfi ...
- Hibernate入门4.核心技能
Hibernate入门4.核心技能 20131128 代码下载 链接: http://pan.baidu.com/s/1Ccuup 密码: vqlv 前言: 前面学习了Hibernate3的基本知识, ...
- Java web实时进度条整个系统共用(如java上传进度条、导入excel进度条等)
先上图: 这上文件上传的: 这是数据实时处理的: 1:先说说什么是进度条:进度条即计算机在处理任务时,实时的,以图片形式显示处理任务的速度,完成度,剩余未完成任务量的大小,和可能需要处理时间,显示方式 ...
- Lotus开发之Lotus Notes中域的验证
一:介绍 Lotus中的域主要有以下的类型:文本,日期/时间,对话框列表,复选框,单选按钮,RTF等等.Lotus中域的验证方式有很多种公式,lotusscript,javascript等 ...
- COM是一个更好的C++
昨天看了<COM本质论>的第一章”COM是一个更好的C++”,觉得很有必要做一些笔记,于是整理成这篇文章,我相信你值得拥有. 这篇文章主要讲的内容是:一个实现了快速查找功能的类FastSt ...
- Windows XP 中设置VPN(PPTP连接方式)
第一步:点开始-网上邻居或者控制面板-网络连接,选择-创建一个新的连接 第二步:点击-下一步 第三步:选择-连接到我的工作场所的网络,点击-下一步 第四步:选择-虚拟专用网络连接,点击-下一步 第五步 ...
- activemq安装与简单消息发送接收实例
安装环境:Activemq5.11.1, jdk1.7(activemq5.11.1版本需要jdk升级到1.7),虚拟机: 192.168.147.131 [root@localhost softwa ...
- Nginx负载均衡深入浅出
nginx不单可以作为强大的web服务器,也可以作为一个反向代理服务器,而且nginx还可以按照调度规则实现动态.静态页面的分离,可以按照轮询.ip哈希.URL哈希.权重等多种方式对后端服务器做负载均 ...
- db2 中文表名和字段
建库语句 create db test on D: using codeset GBK territory CN 或者 territory cn codeset 和 territory 都是需要指定 ...
- Azure SoftEther VPN
装个vs2015,想装全组建还得爬墙… 曾经的 Azure OpenVPN 项目 (http://azure-openvpn.github.io/) 好几年木有更新 改用 SoftEther VPN ...