C# 多线程操作之异步委托

在应届生找工作的时候,多线程操作几乎是所有的公司都会问及的一个基本问题。
这里做了一个多线程操作的总结,这里总结了通过异步委托来实现多线程操作。
定义一个委托,是创建一个线程的最简单的方法,并且异步调用它。委托是方法的类型安全的引用。同时委托还智齿异步调用方法。
委托使用线程池来完成异步任务。
当自己的程序使用异步委托的时候,委托会自动创建ige执行线程的任务。委托使用线程池完成异步任务,所有的异步委托调用,都会通过调用系统线程池中的线程来完成调用异步任务。
在下面的简单例子中,我们定义了一个异步委托,并在每次输出的时候显示该函数运行在哪个线程中。
在异步委托中,可以使用三种技术来异步的调用委托。下面分别介绍三种调用异步委托的方法。
1. 投票判断异步委托是否完成
在委托中调用BeginInvoke()方法,返回IAsyncResult结果。程序的源代码如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace AsyncDelegate
- {
- class Program
- {
- public delegate int TakeSomeTimeDelegate(int data,int ms);
- static void Main(string[] args)
- {
- TakeSomeTimeDelegate dl=TakeSomeTime;
- IAsyncResult ar=dl.BeginInvoke(1,200,null,null);
- while (!ar.IsCompleted)
- {
- Console.WriteLine(".");
- Console.WriteLine("Run in thread:" + Thread.CurrentThread.ManagedThreadId);
- Thread.Sleep(50);
- }
- int result = dl.EndInvoke(ar);
- Console.WriteLine("Result:{0}", result);
- }
- static int TakeSomeTime(int data, int ms)
- {
- Console.WriteLine("TakeSomeTime started!");
- Console.WriteLine("Run in thread:"+Thread.CurrentThread.ManagedThreadId);
- Thread.Sleep(ms);
- Console.WriteLine("TakeSomeTime Completed!");
- return ++data;
- }
- }
- }
该程序的输出结果如图:
可以看到主线程和异步委托线程是同时执行的。
如果在委托结束之前不等待委托完成其他任务就结束主线程,委托线程就会停止。
int result = dl.EndInvoke(ar); 这里的EndInvoke()函数会一直等在异步委托完成并在异步委托完成之前阻断主线程。这样就可以通过这个函数保证异步委托能够正确完成。
2. 等待句柄判断异步委托完成
通过AsyncWatiHandle属性,访问等待句柄。WaitOne()方法阻断当前线程,直到异步调用线程完成返回可以利用的句柄以后再执行当前线程。
程序:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace AsyncDelegate
- {
- class Program
- {
- public delegate int TakeSomeTimeDelegate(int data,int ms);
- static void Main(string[] args)
- {
- TakeSomeTimeDelegate dl=TakeSomeTime;
- IAsyncResult ar=dl.BeginInvoke(1,200,null,null);
- while (true)
- {
- Console.WriteLine(".");
- Console.WriteLine("Run in thread:" + Thread.CurrentThread.ManagedThreadId);
- if (ar.AsyncWaitHandle.WaitOne(100, false))
- {
- Console.WriteLine("Can get the result now");
- break;
- }
- }
- //while (!ar.IsCompleted)
- //{
- // Console.WriteLine(".");
- // Console.WriteLine("Run in thread:" + Thread.CurrentThread.ManagedThreadId);
- // Thread.Sleep(50);
- //}
- int result = dl.EndInvoke(ar);
- Console.WriteLine("Result:{0}", result);
- }
- static int TakeSomeTime(int data, int ms)
- {
- Console.WriteLine("TakeSomeTime started!");
- Console.WriteLine("Run in thread:"+Thread.CurrentThread.ManagedThreadId);
- Thread.Sleep(ms);
- Console.WriteLine("TakeSomeTime Completed!");
- return ++data;
- }
- }
- }
运行结果:
ar.AsyncWaitHandle.WaitOne()阻断了当前线程, 直到异步调用线程完成获得可以利用的句柄以后再次执行当前线程。
3. 利用异步回调函数判断异步调用线程是否结束
回调函数的操作比较复杂, 而且对于程序的理解和维护造成非常大的困难。所以一般情况下能不用回调函数就不要使用回调函数。
使用回调函数,必须注意这个函数从委托线程中调用,而不是从主线程中调用回调函数。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace AsyncDelegate
- {
- class Program
- {
- public delegate int TakeSomeTimeDelegate(int data,int ms);
- static void Main(string[] args)
- {
- TakeSomeTimeDelegate dl=TakeSomeTime;
- IAsyncResult ar = dl.BeginInvoke(1, 200, TakeSomeTimeCompleted, dl);
- for (int i = 0; i < 10;i++ )
- {
- Console.WriteLine(".");
- Console.WriteLine("Run in thread:" + Thread.CurrentThread.ManagedThreadId);
- Thread.Sleep(50);
- }
- //int result = dl.EndInvoke(ar);
- //Console.WriteLine("Result:{0}", result);
- }
- static int TakeSomeTime(int data, int ms)
- {
- Console.WriteLine("TakeSomeTime started!");
- Console.WriteLine("Run in thread:"+Thread.CurrentThread.ManagedThreadId);
- Thread.Sleep(ms);
- Console.WriteLine("TakeSomeTime Completed!");
- return ++data;
- }
- static void TakeSomeTimeCompleted(IAsyncResult ar)
- {
- if (ar==null)
- {
- throw new ArgumentNullException("ar");
- }
- TakeSomeTimeDelegate dl = ar.AsyncState as TakeSomeTimeDelegate;
- int result = dl.EndInvoke(ar);
- Console.WriteLine("result : {0}", result);
- //Console.WriteLine("Run in thread:" + Thread.CurrentThread.ManagedThreadId);
- }
- }
- }
运行结果:
C# 多线程操作之异步委托的更多相关文章
- 6.26学习 异步委托回调函数 VS 多线程 VS 并行处理
描述: 我现在是轮询着构建实例,然后这个实例去执行一个方法,但是执行方法需要大约10s时间,全部轮询下来需要很长时间.所以我现在要更改,头给了我两个方法,1多线程 2异步委托回调函数. 异步委托回调函 ...
- 异步委托(APM)使用Func异步操作,处理耗时操作
使用委托进行异步操作,处理一些耗时操作,防止主线程阻塞 使用例子: using System; using System.Collections.Generic; using System.Linq; ...
- C#实现异步编程的两个简单机制(异步委托&定时器)及Thread实现多线程
创建线程的常用方法:异步委托.定时器.Thread类 理解程序.进程.线程三者之间的区别:简而言之,一个程序至少有一个进程,一个进程至少有一个线程进程就是在内存中运行的程序(即运行着的程序):一个进程 ...
- 异步委托 多线程实现摇奖器 winform版
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using Sy ...
- c# 委托访问listbox多线程操作
c# 委托访问listbox多线程操作 using System;using System.Collections.Generic;using System.ComponentModel;using ...
- C#中级-常用多线程操作(持续更新)
一.前言 多线程操作一直是编程的常用操作,掌握好基本的操作可以让程序运行的更加有效.本文不求大而全,只是将我自己工作中常常用到的多线程操作做个分类和总结.平时记性不好的时候还能看看.本文参 ...
- C#多线程操作界面控件的解决方案(转)
C#中利用委托实现多线程跨线程操作 - 张小鱼 2010-10-22 08:38 在使用VS2005的时候,如果你从非创建这个控件的线程中访问这个控件或者操作这个控件的话就会抛出这个异常.这是微软为了 ...
- 通俗易懂,C#如何安全、高效地玩转任何种类的内存之Span的脾气秉性(二)。 异步委托 微信小程序支付证书及SSL证书使用 SqlServer无备份下误删数据恢复 把list集合的内容写入到Xml中,通过XmlDocument方式写入Xml文件中 通过XDocument方式把List写入Xml文件
通俗易懂,C#如何安全.高效地玩转任何种类的内存之Span的脾气秉性(二). 前言 读完上篇<通俗易懂,C#如何安全.高效地玩转任何种类的内存之Span的本质(一).>,相信大家对sp ...
- c# Winform 多线程操作
主要是对一个过程需要的时间很长执行时会出现界面假死的情况 方法1: Application.DoEvents(),这种方法当你拖动窗体时,界面不会假死.但在你拖动时代码不再执行,也就是阻塞了,当你不再 ...
随机推荐
- Python全栈开发:装饰器实例
#!/usr/bin/env python # -*- coding;utf-8 -*- """ 1.将outer函数放入内存 2.遇见@ + 函数名,则将该函数转换为装 ...
- HTML - 内嵌标签相关
<html> <head></head> <body> <!-- iframe (内嵌标签) src : 要显示的网页资源路径(本地资源或网络资源 ...
- JWT生成token
1.JWT简介 JSON Web Token 简称JWT.一个JWT实际上就是一个字符串,它由三部分组成,头部.载荷与签名.JWT生成的token是这样的 2.Json Web Token(JWT)生 ...
- C++ Builder获取系统文件的路径
取得路径的程序:(注意红色字体,由于博客显示问题,所以中间加了空格,大家自己把空格去掉即可) // -------------------------------------------------- ...
- LUOGU P2344 奶牛抗议 (树状数组优化dp)
传送门 解题思路 树状数组优化dp,f[i]表示前i个奶牛的分组的个数,那么很容易得出$f[i]=\sum\limits_{1\leq j\leq i}f[j-1]*(sum[i]\ge sum[j- ...
- splay区间翻转
原题P3391 [模板]文艺平衡树(Splay) 题目背景 这是一道经典的Splay模板题——文艺平衡树. 题目描述 您需要写一种数据结构(可参考题目标题),来维护一个有序数列,其中需要提供以下操作: ...
- 19-11-12-Aftern-℘
我饿死了,于是写写博客安慰一下即将退役的自己. ZJ: T1. 三种颜色,想到一道神奇的‘天空龙’. 于是觉得此题可做. 那好了. 于是切掉,还拿了一个暴力对拍.疯狂A. 啊dfs慢的要死了 T2一眼 ...
- 19-11-1-N
就剩一个键了…… 以后怎么办呢? 也许可以试试字符映射表……(滑稽 ZJ一下: 我还以为我要死了…… 40 Miemeng 10 03:21:50 80 03:21:51 10 03:21:51 10 ...
- 从xmlns的作用说起
查了资料和自己实践后,得出了一些关于xml和xmlns的结论 看一个最常见的javaweb 中xml配置文件的开头: <?xml version="1.0" encoding ...
- <jsp:forward page=""></jsp:forward>标签失效异常
解决方案:在web.xml <filter-mapping> <filter-name>struts2</filter-name> ...