風語·深蓝

Agile Methodology, HeadStorm And MindMap, they will change me.

导航

委托的复习

Posted on 2006-04-11 21:40  風語者·疾風  阅读(471)  评论(0编辑  收藏  举报
今天群里有个人问怎么检测串口是否存在,告诉他大致的办法就是一个个的去打开,看是否会抛异常,而且最好需要考虑到异步调用会比较好。不过他貌似不会写。不过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(
"检查失败,端口不存在");
            }

        }

    }

}