zoukankan
html css js c++ java
委托的复习
今天群里有个人问怎么检测串口是否存在,告诉他大致的办法就是一个个的去打开,看是否会抛异常,而且最好需要考虑到异步调用会比较好。不过他貌似不会写。不过VS2005下操作串口就非常简单了,我回来花了10分钟写了一个,却由此引起我对委托的一些回顾,总结一下如下:
1、多播委托似乎不能进行异步调用,或者需要明确指明一个调用。
2、多播委托只能返回最后一个注册方法的返回值。
3、异步调用的返回值只能通过EndInvoke方法获取到。
4、BeginInvoke方法中的AsyncCallBack参数是,当异步调用完成的时候发生的回调委托,最后一个object参数是传递给回调委托的参数。
最后贴上今天写的那个检测串口的代码:
using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Runtime.Remoting.Messaging;
namespace
ConsoleApplication
{
class
Program
{
//
定义委托
public
delegate
bool
CheckCOMMethodDelegate(
string
strPortName);
static
void
Main(
string
[] args)
{
CheckCOMMethodDelegate checkDelegate
=
null
;
checkDelegate
+=
new
CheckCOMMethodDelegate(CheckCOM);
//
遍历COM1~COM4
for
(
int
i
=
1
; i
<
5
; i
++
)
{
System.Console.WriteLine(
"
Wating
.Checking COM
"
+
i.ToString());
//
异步调用方法,并使用了回调
IAsyncResult result
=
checkDelegate.BeginInvoke(
"
COM
"
+
i.ToString(), AsyncCallbackMethod, checkDelegate);
while
(
!
result.IsCompleted)
{
System.Console.WriteLine(
"
Wating
.Checking COM
"
+
i.ToString());
System.Threading.Thread.Sleep(
60
);
}
}
System.Console.ReadLine();
}
/**/
///
<summary>
///
检查某端口是否存在,并返回布尔值
///
</summary>
///
<param name="strPortName"></param>
///
<returns></returns>
protected
static
bool
CheckCOM(
string
strPortName)
{
using
(System.IO.Ports.SerialPort p
=
new
System.IO.Ports.SerialPort(strPortName))
{
try
{
p.Open();
}
catch
{
return
false
;
}
}
return
true
;
}
/**/
///
<summary>
///
当异步调用完成之后调用的回调方法:根据返回结果进行不同的输出
///
</summary>
///
<param name="result"></param>
protected
static
void
AsyncCallbackMethod(IAsyncResult result)
{
CheckCOMMethodDelegate methodDelegate
=
(CheckCOMMethodDelegate)result.AsyncState;
bool
IsSuccess
=
methodDelegate.EndInvoke(result);
if
(IsSuccess)
{
System.Console.WriteLine(
"
端口存在
"
);
}
else
{
System.Console.WriteLine(
"
检查失败,端口不存在
"
);
}
}
}
}
查看全文
相关阅读:
初涉网络安全领域
pythontip上的数据结构和算法练习题
学c++需要先学c语言吗?
田园将芜胡不归
java学习视频
微软越来越喜欢Github(转载)
指针(一级指针、二级指针)
数字盒子
点结构Tpoint
枚举类型
原文地址:https://www.cnblogs.com/Xrinehart/p/372629.html
最新文章
Missing artifact ojdbc:ojdbc:jar:14启动Maven项目报错提示
org.hibernate.hql.internal.ast.QuerySyntaxException: XXX is not mapped
windows7 中强烈建议禁用以关闭的系统服务
ORA-12560: TNS: 协议适配器错误
The prefix "context" for element "context:property-placeholder" is not bound.
Exception in thread "main" java.sql.SQLException: ORA-01017: invalid username/password; logon denied
私藏很久的C语言开源项目,这次贡献了!(转载)
lua
永久关闭win10自动更新
解决VS2013中出现类似于error C4996: 'scanf': This function or variable may be unsafe的安全检查错误
热门文章
The Write Great Code Series (编程卓越之道 共6卷)
HLA汇编语言
ASCII码表
解决VS2019中出现类似于error C4996: 'scanf': This function or variable may be unsafe的安全检查错误
error C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conf
EasyX
代码随想录
重温C语言
三个数据结构和算法可视化网站
VC2010编译C程序结束后黑框一闪,嘿嘿,如何解决?嘿嘿
Copyright © 2011-2022 走看看