コード例 #1
0
ファイル: PingAsync.cs プロジェクト: 15831944/NFramework
        /// <summary>
        /// Internet Control Message Protocol (ICMP) echo message 를 비동기적으로 보냅니다.
        /// </summary>
        private static Task <PingReply> SendTaskCore(Ping ping, object userToken, Action <TaskCompletionSource <PingReply> > sendAsync)
        {
            ping.ShouldNotBeNull("ping");
            sendAsync.ShouldNotBeNull("sendAsync");

            if (IsDebugEnabled)
            {
                log.Debug("Ping 작업을 비동기적으로 수행하는 Task를 생성합니다...");
            }

            var tcs = new TaskCompletionSource <PingReply>(userToken);
            PingCompletedEventHandler handler = null;

            handler             = (sender, e) => EventAsyncPattern.HandleCompletion(tcs, e, () => e.Reply, () => ping.PingCompleted -= handler);
            ping.PingCompleted += handler;

            try {
                sendAsync(tcs);
            }
            catch (Exception ex) {
                ping.PingCompleted -= handler;
                tcs.TrySetException(ex);
            }

            return(tcs.Task);
        }
コード例 #2
0
        /// <summary>The core implementation of SendTask.</summary>
        /// <param name="ping">The Ping.</param>
        /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
        /// <param name="sendAsync">
        /// A delegate that initiates the asynchronous send.
        /// The provided TaskCompletionSource must be passed as the user-supplied state to the actual Ping.SendAsync method.
        /// </param>
        /// <returns></returns>
        private static Task <PingReply> SendTaskCore(
            Ping ping, object userToken, Action <TaskCompletionSource <PingReply> > sendAsync)
        {
            // Validate we're being used with a real smtpClient.  The rest of the arg validation
            // will happen in the call to sendAsync.
            if (ping == null)
            {
                throw new ArgumentNullException(nameof(ping));
            }

            // Create a TaskCompletionSource to represent the operation
            var tcs = new TaskCompletionSource <PingReply>(userToken);

            // Register a handler that will transfer completion results to the TCS Task
            PingCompletedEventHandler handler = null;

            handler             = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Reply, () => ping.PingCompleted -= handler);
            ping.PingCompleted += handler;

            // Try to start the async operation.  If starting it fails (due to parameter validation)
            // unregister the handler before allowing the exception to propagate.
            try
            {
                sendAsync(tcs);
            }
            catch (Exception exc)
            {
                ping.PingCompleted -= handler;
                tcs.TrySetException(exc);
            }

            // Return the task to represent the asynchronous operation
            return(tcs.Task);
        }
コード例 #3
0
    private static Task <PingReply> SendTaskAsyncCore(Ping ping, object userToken, Action <TaskCompletionSource <PingReply> > sendAsync)
    {
        if (ping == null)
        {
            throw new ArgumentNullException("ping");
        }
        TaskCompletionSource <PingReply> tcs     = new TaskCompletionSource <PingReply>(userToken);
        PingCompletedEventHandler        handler = null;

        handler = delegate(object sender, PingCompletedEventArgs e)
        {
            AsyncCompatLibExtensions.HandleEapCompletion <PingReply>(tcs, true, e, () => e.Reply, delegate
            {
                ping.PingCompleted -= handler;
            });
        };
        ping.PingCompleted += handler;
        try
        {
            sendAsync(tcs);
        }
        catch
        {
            ping.PingCompleted -= handler;
            throw;
        }
        return(tcs.Task);
    }
コード例 #4
0
 /// <summary>
 /// Event is raised on ping result
 /// </summary>
 /// <param name="inTgt">Hostname or IP. Not verified</param>
 /// <param name="inH">Do NOT invoke with null</param>
 /// <exception cref="ArgumentException"></exception>
 public static void PingWithEvent(
     string inTgt,
     PingCompletedEventHandler inH)
 {
     if (inH == null)
     {
         throw new ArgumentException("null event handler");
     }
     //exception <-> not setting empty delegate
     //https://stackoverflow.com/questions/4303343/is-it-a-good-practice-to-define-an-empty-delegate-body-for-a-event
     lock (_buff)
     {
         //... cannot use the same instance of the Ping class...
         Ping doer = new Ping();//doers do
         doer.PingCompleted += inH;
         Task.Run(() =>
         {
             //https://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping(v=vs.110).aspx
             //NOTICE:
             //`UserState` token is set with `AutoResetEvent`
             //Here (see last arg),
             //the `UserState` is set with the supplied string
             doer.SendAsync(
                 inTgt,
                 GY_PINGER_DEFAULT_TIMEOUT,
                 _buff,
                 _opt,
                 inTgt);
         });
     }//lock
 }
コード例 #5
0
        public static Task <string> PingTask(this DataService client, TaskCompletionSource <string> tcs)
        {
            PingCompletedEventHandler handler = null;

            try {
                handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Result, () => client.PingCompleted -= handler);
                client.PingCompleted += handler;

                client.PingAsync(tcs);
            }
            catch (Exception ex) {
                if (log.IsErrorEnabled)
                {
                    log.ErrorException("웹서비스 비동기 호출에 예외가 발생했습니다.", ex);
                }

                if (handler != null)
                {
                    client.PingCompleted -= handler;
                }

                tcs.TrySetException(ex);
            }
            return(tcs.Task);
        }
コード例 #6
0
        /**
         * Extension method Curtosy of SO user L.B.
         * http://stackoverflow.com/a/25534776
         **/
        public static Task <PingResult> SendTaskAsync(this Ping ping, string address)
        {
            var tcs = new TaskCompletionSource <PingResult>();
            PingCompletedEventHandler response = null;

            response = (s, e) =>
            {
                ping.PingCompleted -= response;
                if (e.Reply != null)
                {
                    tcs.SetResult(new PingResult()
                    {
                        DestinationAddress = address,
                        SourceAddress      = e.Reply?.Address.ToString(),
                        Status             = e.Reply?.Status.ToString(),
                        RoundtripTime      = (long)e.Reply?.RoundtripTime,
                        TimeToLive         = e.Reply.Options?.Ttl ?? -1
                    });
                }
                else
                {
                    tcs.SetResult(new PingResult()
                    {
                        DestinationAddress = address,
                        SourceAddress      = "0.0.0.0",
                        Status             = "INVALID",
                        RoundtripTime      = -1,
                        TimeToLive         = -1
                    });
                }
            };
            ping.PingCompleted += response;
            ping.SendAsync(address, address);
            return(tcs.Task);
        }
コード例 #7
0
 private void HandleCompletion(TaskCompletionSource <PingReply> tcs, PingCompletedEventArgs e, PingCompletedEventHandler handler)
 {
     if (e.UserState == tcs)
     {
         try
         {
             PingCompleted -= handler;
         }
         finally
         {
             if (e.Error != null)
             {
                 tcs.TrySetException(e.Error);
             }
             else if (e.Cancelled)
             {
                 tcs.TrySetCanceled();
             }
             else
             {
                 tcs.TrySetResult(e.Reply);
             }
         }
     }
 }
コード例 #8
0
        /// <summary>
        /// Really fast parallel ping for IPs list .Return new list with respounded IPs.
        /// </summary>
        public static async Task <List <string> > Ping(ICollection <string> inputIPs, int timeoutMS = 50)
        {
            List <string> res = new List <string>();

            Pool <Ping> pingersPool = new Pool <Ping>(null, 500);
            List <Task <PingReply> >  pingersTasks = new List <Task <PingReply> >(inputIPs.Count);
            PingCompletedEventHandler ev           = null;

            ev = (sender, evArgs) =>
            {
                ((Ping)sender).PingCompleted -= ev;
                if (evArgs.Reply.Status == IPStatus.Success)
                {
                    res.Add(evArgs.Reply.Address.ToString());
                }
                pingersPool.PutObject((Ping)sender);
            };
            foreach (string ipStr in inputIPs)
            {
                IPAddress address = IPAddress.Parse(ipStr);
                var       pinger  = pingersPool.GetObject();

                pinger.PingCompleted += ev;
                pingersTasks.Add(pinger.SendPingAsync(ipStr, timeoutMS));
            }

            await Task.WhenAll(pingersTasks).ConfigureAwait(false);;

            pingersPool.ClearPool();
            return(res);
        }
コード例 #9
0
ファイル: PingExtensions.cs プロジェクト: ithanshui/Common-2
        /// <summary>The core implementation of SendTask.</summary>
        /// <param name="ping">The Ping.</param>
        /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
        /// <param name="sendAsync">
        /// A delegate that initiates the asynchronous send.
        /// The provided TaskCompletionSource must be passed as the user-supplied state to the actual Ping.SendAsync method.
        /// </param>
        /// <returns></returns>
        private static Task <PingReply> SendTaskCore(Ping ping, object userToken, Action <TaskCompletionSource <PingReply> > sendAsync)
        {
            if (ping == null)
            {
                throw new ArgumentNullException("ping");
            }
            TaskCompletionSource <PingReply> tcs     = new TaskCompletionSource <PingReply>(userToken);
            PingCompletedEventHandler        handler = null;

            handler = delegate(object sender, PingCompletedEventArgs e) {
                EAPCommon.HandleCompletion <PingReply>(tcs, e, () => e.Reply, delegate {
                    ping.PingCompleted -= handler;
                });
            };
            ping.PingCompleted += handler;
            try
            {
                sendAsync(tcs);
            }
            catch (Exception exception)
            {
                ping.PingCompleted -= handler;
                tcs.TrySetException(exception);
            }
            return(tcs.Task);
        }
コード例 #10
0
ファイル: Ping.cs プロジェクト: dekkerb115/Bam.Net
        private void OnPingCompleted(PingResponse response)
        {
            PingCompletedEventHandler temp = PingCompleted;

            if (temp != null)
            {
                temp(this, new PingCompletedEventArgs(response, DateTime.Now));
            }
        }
コード例 #11
0
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// pingcompletedeventhandler.BeginInvoke(sender, e, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this PingCompletedEventHandler pingcompletedeventhandler, Object sender, PingCompletedEventArgs e, AsyncCallback callback)
        {
            if (pingcompletedeventhandler == null)
            {
                throw new ArgumentNullException("pingcompletedeventhandler");
            }

            return(pingcompletedeventhandler.BeginInvoke(sender, e, callback, null));
        }
コード例 #12
0
ファイル: MultiPing.cs プロジェクト: tuzhongyi/Howell.Core
        /// <summary>
        /// 引发 System.Net.NetworkInformation.Ping.PingCompleted 事件。
        /// </summary>
        /// <param name="e">包含事件数据的 System.Net.NetworkInformation.PingCompletedEventArgs 对象。</param>
        protected void OnSinglePingCompleted(PingCompletedEventArgs e)
        {
            PingCompletedEventHandler handler = SinglePingCompleted;

            if (handler != null)
            {
                handler(this, e);
            }
        }
コード例 #13
0
        private static void _inputLoopEvent()
        {
            var    dlgt  = new PingCompletedEventHandler(_OnPingCompleted);
            string aLine = null;

            while (true)
            {
                aLine = Console.ReadLine();//blocks
                if (aLine == null)
                {
                    break;//<-> ctrl+Z+Enter
                }
                GYPinger.PingWithEvent(aLine, dlgt);
            }
        }
コード例 #14
0
    public static Task <PingResult> SendTaskAsync(this Ping ping, string address)
    {
        var tcs = new TaskCompletionSource <PingResult>();
        PingCompletedEventHandler response = null;

        response = (s, e) =>
        {
            ping.PingCompleted -= response;
            tcs.SetResult(new PingResult()
            {
                Address = address, Reply = e.Reply
            });
        };
        ping.PingCompleted += response;
        ping.SendAsync(address, address);
        return(tcs.Task);
    }
コード例 #15
0
 static void SendPing(int hostIdx, Action <int, bool> onComplete)
 {
     using (Ping pingSender = new Ping())
     {
         PingCompletedEventHandler completed = null;
         completed = (sender, args) =>
         {
             bool succeeded = args.Error == null && !args.Cancelled && args.Reply != null && args.Reply.Status == IPStatus.Success;
             onComplete(hostIdx, succeeded);
             Ping p = sender as Ping;
             p.PingCompleted -= completed;
             p.Dispose();
         };
         pingSender.PingCompleted += completed;
         string      data    = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
         byte[]      buffer  = Encoding.ASCII.GetBytes(data);
         PingOptions options = new PingOptions(64, true);
         pingSender.SendAsync(hosts[hostIdx], 2000, buffer, options, hostIdx);
     }
 }
コード例 #16
0
        public void checkIp(string ip, string key, PingCompletedEventHandler asynEvent)
        {
            try
            {
                IPAddress address = IPAddress.Parse(ip);
                Ping      ping    = new Ping();

                PingOptions po = new PingOptions();
                po.DontFragment = true;

                string data    = "Test Data!";
                byte[] buffer  = Encoding.ASCII.GetBytes(data);
                int    timeout = 3000;

                ping.PingCompleted += asynEvent;
                ping.SendAsync(address, timeout, buffer, po, key);
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
コード例 #17
0
        private Task <PingReply> SendPingAsyncCore(Action <TaskCompletionSource <PingReply> > sendAsync)
        {
            // Create a TaskCompletionSource to represent the operation.
            var tcs = new TaskCompletionSource <PingReply>();

            // Register a handler that will transfer completion results to the TCS Task.
            PingCompletedEventHandler handler = null;

            handler        = (sender, e) => HandleCompletion(tcs, e, handler);
            PingCompleted += handler;

            // Start the async operation.
            try { sendAsync(tcs); }
            catch
            {
                PingCompleted -= handler;
                throw;
            }

            // Return the task to represent the asynchronous operation.
            return(tcs.Task);
        }
コード例 #18
0
ファイル: Pinger.cs プロジェクト: CaptainKEKIS/Host-Monitor
        private Task <Tuple <PingReply, object> > PingAsync(Ping ping, IPAddress epIP)
        {
            try
            {
                var tcs = new TaskCompletionSource <Tuple <PingReply, object> >();
                PingCompletedEventHandler act = null;

                act = (obj, sender) =>
                {
                    ping.PingCompleted -= act;
#if DEBUG
                    Console.WriteLine($"host: {sender.UserState}\tdelay: {((sender.Reply != null) ? (sender.Reply.Status != IPStatus.Success) ? -1 : ((int)sender.Reply.RoundtripTime == 0) ? 1 : (int)sender.Reply.RoundtripTime : -1)}\tstatus: {((sender.Reply != null) ? sender.Reply.Status : IPStatus.Unknown)}");
#endif
                    tcs.SetResult(Tuple.Create(sender.Reply, sender.UserState));
                };
                ping.PingCompleted += act;
                ping.SendAsync(epIP, TimeOut, PingBuffer, POptions, epIP);
                return(tcs.Task);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
コード例 #19
0
ファイル: ping.cs プロジェクト: rainersigwald/corefx
 private void HandleCompletion(TaskCompletionSource<PingReply> tcs, PingCompletedEventArgs e, PingCompletedEventHandler handler)
 {
     if (e.UserState == tcs)
     {
         try
         {
             PingCompleted -= handler;
         }
         finally
         {
             if (e.Error != null) tcs.TrySetException(e.Error);
             else if (e.Cancelled) tcs.TrySetCanceled();
             else tcs.TrySetResult(e.Reply);
         }
     }
 }