必须把事件处理函数放到构造函数里面,如果放在listen函数里面。那么两次的listen调用就会执行两次触发事件。看了事件处理机制和半天程序才找出来原因。...

Timer2.Elapsed += new ElapsedEventHandler(Timer2_ElapsedEventHandler);

必须把事件处理函数放到构造函数里面,如果放在listen函数里面。那么两次的listen调用就会执行两次触发事件。

看了事件处理机制和半天程序才找出来原因。using System; using System.IO; using System.IO.Pipes; using System.Linq; using System.Text; using System.Threading; using System.Collections.Generic; using System.Security.Principal; using System.Timers; namespace NewTools1 { class NewTools1 { static System.Timers.Timer Timer2 = new System.Timers.Timer(10000); static NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "loopholepipe", PipeDirection.InOut); static StreamReader sr = new StreamReader(pipeClient); static StreamWriter sw = new StreamWriter(pipeClient); public NewTools1() { //必须把事件处理函数放到构造函数里面,如果放在listen函数里面。那么两次的listen调用就会执行两次触发事件。 //看了事件处理机制和半天程序才找出来原因。 Timer2.Elapsed += new ElapsedEventHandler(Timer2_ElapsedEventHandler); } public void listen() { //最好写个初始化类将下语句包含进去。 // Connect to the pipe or wait until the pipe is available. if (pipeClient.IsConnected == false) { Console.Write("Attempting to connect to pipe..."); pipeClient.Connect(); Console.WriteLine("Connected to pipe."); Console.WriteLine("There are currently {0} pipe server instances open.", pipeClient.NumberOfServerInstances); } // Display the read text to the console string temp = null; temp = sr.ReadLine(); Console.WriteLine("Received from ToolsManagement: {0},开始执行任务", temp); //任务执行命令 Timer2.Start(); try { // Read user input and send that to the client process. Thread.Sleep(35000); sw.AutoFlush = true; //Console.Write("Enter text: "); //sw.WriteLine(Console.ReadLine()); sw.WriteLine("the task is finished"); Console.WriteLine("任务执行完毕"); //将定时器关掉 Timer2.Close(); } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { Console.WriteLine("ERROR: {0}", e.Message); } } private static void Timer2_ElapsedEventHandler(object sender, ElapsedEventArgs e) { Console.WriteLine("timer2TimeOut发送工具存活消息"); //还用不用捕捉异常 sw.AutoFlush = true; string temp1 = "the tool is alive"; sw.WriteLine(temp1); } static void Main(string[] args) { NewTools1 newtool = new NewTools1(); newtool.listen(); Console.WriteLine("输入回车进入下一监听函数"); Console.ReadLine(); newtool.listen(); Console.Write("Press Enter to continue..."); Console.ReadLine(); } } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值