【问题标题】:Continuous Async Ping inside a Windows ServiceWindows 服务中的连续异步 Ping
【发布时间】:2020-05-26 03:38:53
【问题描述】:

我需要持续监控主机列表。 N秒后,我需要再次检查列表。因此,我尝试在 Windows 服务中使用异步 ping。

我尝试遵循与该主题相关的其他帖子中的提示,但我的服务总是在启动后不久停止。

“OnElapsedTime”函数中的await有问题。

有人知道出了什么问题吗?咆哮我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Net.NetworkInformation;

namespace PingAsyncService
{
    public partial class HyBrazil_Ping : ServiceBase

    {

        Timer timer = new Timer();
        List<string> IPList = new List<string>();  //List of IPs


        public HyBrazil_Ping()
        {
            IPList.Add("192.168.0.1");
            IPList.Add("192.168.0.254");

            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            WriteToFile("Service is started at " + DateTime.Now);
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 5000; //number in miliseconds 
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            WriteToFile("Service is stopped at " + DateTime.Now);
        }

        private async void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            //WriteToFile("Service is recall at " + DateTime.Now);

            var ResultList = await PingAsync();
            foreach(PingReply reply in ResultList)
            {
                WriteToFile(reply.Address.ToString() + ";" + reply.Status.ToString());
            }
        }

        private async Task<PingReply> PingAndProcessAsync(Ping pingSender, string ip)
        {
            var result = await pingSender.SendPingAsync(ip, 2000);
            return result;
        }

        private async Task<List<PingReply>> PingAsync()
        {
            Ping pingSender = new Ping();
            var tasks = IPList.Select(ip => PingAndProcessAsync(pingSender, ip));
            var results = await Task.WhenAll(tasks);
            return results.ToList();
        }

        public void WriteToFile(string Message)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
            if (!File.Exists(filepath))
            {
                // Create a file to write to.   
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
        }
    }
}

非常感谢!

【问题讨论】:

  • 您很可能在异步 void 方法中遇到异常,这会导致在线程池线程上抛出异常,然后将其崩溃。包裹在 try catch 块中并查看
  • 好的,异常消息是:“异步调用已经在进行中。必须先完成或取消才能调用此方法。”。然后,问题出在“await Task.WhenAll(tasks);”中在 PingAsync 函数中。我如何解决这个问题? async函数正确返回,但调用没有结束
  • 您的计时器间隔每 5 秒触发一次,因此即使操作尚未完成,它也会再次调用它。为计时器设置 AutoReset = false 并手动重新启动它
  • 但是操作完成了!问题不是时间。我在 txt 文件中看到了第一次操作的成功,但我无法触发其他调用
  • 我的猜测是您需要为每个 IP 创建一个单独的 Ping 对象。单个Ping 可能无法执行多个并发操作。你也可以看看periodic async calls 的不同技术,而不是使用计时器。

标签: c# service async-await windows-services ping


【解决方案1】:

在您提到的错误消息之一中,错误消息为 "一个异步调用已经在进行中。必须先完成或取消它才能调用此方法。"

很有可能,Ping 对象不允许同时进行异步调用。 每次调用时使用新的 Ping 对象可能会有所帮助,如下所示。

private async Task<List<PingReply>> PingAsync()
{
    // Ping pingSender = new Ping();
    var tasks = IPList.Select(ip =>
    {
        using (var p= new Ping())
        {
            return PingAndProcessAsync(p, ip);
        }
    });
    var results = await Task.WhenAll(tasks);
    return results.ToList();
}

【讨论】:

    猜你喜欢
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2020-06-25
    • 2013-01-24
    • 2018-01-25
    相关资源
    最近更新 更多