Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi guys,

I have written a code for my forms application, this application scans all active IP's in a big range using PING.ASYNC. I used a windows MSDN exmaple for this.

When i run this code in my forms application some ping returns with a delay of +/- 10 seconds, or worse some never...

When i run the EXACT the same code with a consule application all my result get back within a timespan of 500 milleseconds.

Code example consule :

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Siemens;
using IPScanner;

namespace ConsuleInterface
{
    class Program
    {
        static void Main(string[] args)
        {
            Scanner Scanner = new Scanner();
            StringBuilder Scanlist = new StringBuilder();
            Console.WriteLine("Start scan, please wait");
            Scanlist = Scanner.Find("192.168.0.1");
            Console.Write(Scanlist);
            Console.ReadKey();
        }
    }
}


Code example forms :

C#
private void BTN_Scan_IP_Range_Click(object sender, EventArgs e)
{
   TxtDump.Text = "";
   TxtDump.Text = "Starting scan, please wait for 20 seconds for results";
   TxtDump.Text = Scanner.Find(IP_Adres_PLC.Text).ToString();
    //Scan Scan = new Scan();
    //TxtDump.Text = Scan.Start(IP_Adres_PLC.Text).ToString();
}


Source code :

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using Siemens;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;


namespace IPScanner
{
    public class Scanner
    {
        static CountdownEvent countdown;
        static int upCount = 0;
        static object lockObj = new object();
        const bool resolveNames = false;
        static StringBuilder Scanlist = new StringBuilder();

        public StringBuilder Find(string IpAdress)
        {
            string[] IPV6 = IpAdress.Split(new char[] { ':' });
            if (IPV6.Length == 1) // ipv4 or hostname
            {
                                // check format of ipadres - should be a.b.c.d
                string[] IPV4 = IpAdress.Split(new char[] { '.' });
                if (IPV4.Length <= 3)
                {
                    return Scanlist.AppendLine("Invalid IP adress entered, please enter a valid ip adres. Example: (IPv4) 192.168.1.1");                    
                }
                // Check for digits and dots
                foreach (Char c in IpAdress.ToCharArray())
                {
                    if (Char.IsDigit(c)) continue;
                    else if (c == '.') continue;
                    else return Scanlist.AppendLine("Invalid IP adress entered, please enter a valid ip adres. Example: (IPv4) 192.168.1.1");      
                }
                countdown = new CountdownEvent(1);
                Stopwatch sw = new Stopwatch();
                sw.Start();
                for (int i = 1; i <= 254; i++)
                {
                    string IP = string.Format("{0}.{1}.{2}.{3}", IPV4[0], IPV4[1], IPV4[2], i);

                    Ping p = new Ping();
                    p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
                    countdown.AddCount();
                    p.SendAsync(IP, 100, IP);
                }
                countdown.Signal();
                countdown.Wait();
                sw.Stop();
                TimeSpan span = new TimeSpan(sw.ElapsedTicks);
                Scanlist.AppendLine(String.Format("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount));
                return Scanlist;
            }
            else if (IPV6.Length > 2) //ipv6
            {
                return Scanlist.AppendLine("IPv6 is not supported yet");      
            }
            else
            {
                return Scanlist.AppendLine("Invalid IP adress entered, please enter a valid ip adres. Example: (IPv4) 192.168.1.1 or (IPv6) 3ffe:6a88:85a3:08d3:1319:8a2e:0370:7344");      
            }
        }
        public void p_PingCompleted(object sender, PingCompletedEventArgs e)
        {
            S7CpuInfo CPU_Info = new S7CpuInfo();
            string ip = (string)e.UserState;
            if (e.Reply != null && e.Reply.Status == IPStatus.Success)
            {
                string mac = getMAC(IPAddress.Parse(ip));
                Scanlist.AppendLine(string.Format("{0} is online - MAC adres - {1} - response time {2} ms)", ip, mac, e.Reply.RoundtripTime));
                if (Global.PLC.ConnectTo(ip,0,2) == 0)
                {
                    Global.PLC.GetCpuInfo(CPU_Info);
                    string cpuname = "", cputype = "";
                    cpuname = CPU_Info.ModuleName(); cputype = CPU_Info.ModuleTypeName();
                    Scanlist.AppendLine(string.Format("Siemens PLC found - Type {0} -  PLC name {1}", cputype, cpuname));
                }
                else
                {
                    Scanlist.AppendLine(string.Format("Not an Siemens PLC"));
                }
                upCount++;
            }
            else if (e.Reply == null)
            {
                Scanlist.AppendLine(string.Format("Pinging {0} failed. (Null Reply object?)", ip));
            }
            countdown.Signal(1);
        }

        [DllImport("iphlpapi.dll", ExactSpelling = true)]
        public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);

        public static string getMAC(IPAddress address)
        {
            int intAddress = BitConverter.ToInt32(address.GetAddressBytes(), 0);

            byte[] macAddr = new byte[6];
            uint macAddrLen = (uint)macAddr.Length;
            if (SendARP(intAddress, 0, macAddr, ref macAddrLen) != 0)
                return "(NO ARP result)";

            string[] str = new string[(int)macAddrLen];
            for (int i = 0; i < macAddrLen; i++)
                str[i] = macAddr[i].ToString("x2");

            return string.Join(":", str);
            ;
        }
    }
}


Why is the consule so much faster?
How can i speed up my windows forms application?

Hope you guys can give me some answers, thanks in advance!
Posted
Updated 30-Oct-15 4:36am
v2
Comments
Richard Deeming 30-Oct-15 10:01am    
So you want us to tell you why some code that we cannot see is faster than some other code that we cannot see?

Use the "Improve question" button to update your question with the relevant code from both applications.
Djoezy 30-Oct-15 10:55am    
Question improved!
VR Karthikeyan 30-Oct-15 10:11am    
Show your code
Sinisa Hajnal 30-Oct-15 10:13am    
You say it is the same code, but there must be something different. Maybe they are deployed differently, use different polling mechanism, something. Post the code.
BillWoodruff 30-Oct-15 11:01am    
1. how are you timing the results: if you are using DateTime.Now, they may be quite inaccurate.

2. in your use in the Form: are you doing anything that would update the UI when you run your scan ?

1 solution

What's so amazing in different timing results? They should be different. Timings is different just because you wrote more code lines. :-) With UI along, you may spend orders of magnitude of CPU time than for all the computing you want to present in this UI. I would not take it too serious, until the performance becomes annoyingly slow. To keep it short: just use some .NET code profiler to find out where your CPU time goes to:
https://en.wikipedia.org/wiki/Profiling_%28computer_programming%29[^],
https://en.wikipedia.org/wiki/List_of_performance_analysis_tools#.NET[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900