分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

net .异步委托知识

发布时间:2023-09-06 01:23责任编辑:顾先生关键词:暂无标签

 以前在编程中,异步用的比较少,导致C# 一些基础的 东西用法都不怎么熟悉,经常要用的时候在去查找资料比较被动,而已没真正里面理解起来,始终感觉不是自己的知识 (题外话)

  首先委托关键字  Delegate 

 1) 定义  

/// 委托必须和要调用的异步方法有相同的签名
???????public delegate string AsyncMethodCaller(int callDuration, out int threadId);

2. 异步委托的方法 

static string TestMethod(int callDuration, out int threadId)
???????{
???????????Thread.Sleep(callDuration);
???????????threadId = Thread.CurrentThread.ManagedThreadId;
???????????return string.Format("My call time was {0}.", callDuration.ToString());
???????}

3) 调用 

 AsyncMethodCaller caller = new AsyncMethodCaller(TestMethod);

???????????IAsyncResult result = caller.BeginInvoke(10000, out threadId, null, null);
???????????//调用EndInvoke方法,等待异步调用完成,并得到结果。
???????????string returnValue = caller.EndInvoke(out threadId, result);

注意里面几个关键字  BeginInvoke , EndInvoke  IAsyncResult   

  BeginInvoke方法触发你的异步方法,它和你想要执行的异步方法有相同的参数。另外还有两个可选参数,第一个是AsyncCallback委托是异步完成的回调方法。第二个是用户自定义对象,该对象将传递到回调方法中。BeginInvoke立即返回并且不等待完成异步的调用(继续执行该下面的代码,不需要等待)。BeginInvoke返回IAsyncResult接口,可用于检测异步调用的过程。

通过EndInvoke方法检测异步调用的结果。如果异步调用尚未完成,EndInvoke将阻塞调用线程,直到它完成。EndInvoke参数包括out和ref参数。

  当然也可以不用 EndInvoke 来异步检测 可以使用  

第二种 

result .AsyncWaitHandle.WaitOne(); 阻塞当前主线程 知道异步的方法完成回调触法 
result .AsyncWaitHandle.Close();  用完关闭 

第三种方法  

  先定义

1)  AutoResetEvent autoresetevent = new AutoResetEvent(false);

2) 在异步方法里完成时候设置信号 等待回调 autoresetevent.Set();

3)  在主线程 调用异步的方法后 设置等待   autoresetevent.WaitOne();

  还有一种 委托用法 很方便 个人建议使用 后面这种用法 Action 有参数没有方法值   Func 有返回值没参数 

  定义 :

Action<string, string> act = new Action<string, string>(ShowString);

异步方法:

void ShowString(string str, string yy)
{
Thread.Sleep(50000);
}

定义
 Func<bool> methodCall = SendToFile;

异步方法 

public bool SendToFile()
???????{
???????????return true;
???????}

使用后面这种委托的 配合使用NET3.0以后的新特性 Lambda表达式表达式 代码看起来  很简便 不用过多的定义  

例如 

AutoResetEvent autoresetevent = new AutoResetEvent(false);
???????????Action<string, string> act = new Action<string, string>((o, p) =>
???????????{
???????????????Thread.Sleep(5000);
???????????????autoresetevent.Set();

???????????});
???????????act.BeginInvoke("11", "222", null, null);
???????????autoresetevent.WaitOne();
???????????autoresetevent.Close();

 ()=> 表示一个匿名函数,=>前面的是参数,后面的是函数体。 可以把它当作一个函数

   

  

  

net .异步委托知识

原文地址:http://www.cnblogs.com/itch/p/7809878.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved