1

I want to make Pinger with start and stop button, this code i get from this forum like stopLoop:

private bool _stopLoop;
private void button1_Click(object sender, EventArgs e)
{
    _stopLoop = false;

    for (int i = 0; i < 100000 && !_stopLoop; ++i)
    {
        using (Ping p = new Ping())
        {
            lbPing.Text = p.Send(tbUrl.Text).RoundtripTime.ToString() + "ms\n";
            lbPing.Update();
        }
    }
}

protected override void WndProc(ref Message m)
{
    switch (m.Msg)
    {
        case 0x84:
            base.WndProc(ref m);
            if ((int)m.Result == 0x1)
                m.Result = (IntPtr)0x2;
            return;
    }

    base.WndProc(ref m);
}

private void btStop_Click(object sender, EventArgs e)
{
    _stopLoop = true;
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • 1
    [MSDN](https://msdn.microsoft.com/de-de/library/hb7xxkfx(v=vs.110).aspx) _This method sends to the host that is specified by address a 32 Byte data buffer with the ICMP echo message. __The method waits five seconds__ for an ICMP echo reply message. If it does not receive a reply in that time, the method returns and the Status property is set to TimedOut_ – TaW Sep 08 '18 at 07:07

3 Answers3

2

Just use the async and await pattern to free up the UI

private async void button1_Click(object sender, EventArgs e)
{
   _stopLoop = false;

   while( !_stopLoop)
   {  
      using (var p = new Ping())
      {
         var pingReply = await p.SendPingAsync(IPAddress.Parse("1.1.1.1"), 10000);
         lbPing.Text = $"{pingReply.RoundtripTime} ms";
         await Task.Delay(1000);
      }
   }
}

Additional resources

SendPingAsync(IPAddress, Int32)

Send an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified IPAddress, and receives a corresponding ICMP echo reply message from that computer as an asynchronous operation. This overload allows you to specify a time-out value for the operation.

Parameters

  • address IPAddress

An IP address that identifies the computer that is the destination for the ICMP echo message.

  • timeout Int32

The maximum number of milliseconds (after sending the echo message) to wait for the ICMP echo reply message.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0

I think Your Stop Button is not working Because your:

loop= for (int i = 0; i < 100000 && !_stopLoop; ++i)

In this loop _stopLoop variable is always true because you are using the ! Operator.

MBT
  • 21,733
  • 19
  • 84
  • 102
0

Because the execution thread that is responsible for processing window messages (your button click) is busy performing the code you have written. Your code blocks (prevents) the thread from returning to its normal job of keeping the UI responsive to interaction. It is a common thing we have to consider when writing windows apps, not to block (keep busy) the thread that started executing the code in the button click handler. In simple terms, you have to let the thread that entered your click handler exit it again as soon as possible. In your case you have instead sent it off into a method that doesn't come back to your code for 5 seconds when what you need to do is use it to start a separate execution of the long running method, and then let it go back to processing UI updates

We do this by running the work code asynchronously or using a mechanism that will create [something like] a separate thread for it

Using async: https://learn.microsoft.com/en-us/windows/uwp/debug-test-perf/keep-the-ui-thread-responsive

Using backgroundworker: How to use a BackgroundWorker?

(I'm deliberately avoiding linking anything that encourages you to directly create and manage your own threads. The above two mechanisms are more appropriate for modern applications)

As a side info, windows essentially works by apps having a message queue (first in first out). Everything you do (move the mouse, click, press keys) gets posted into this queue and your program has a thread that works through the events and acts on them. If you keep that thread busy for seconds on end doing your code, it won't consume messages. The operating system notices that the queue is getting longer and longer, and fades the window/puts "not responding" in the title. As soon as the ui thread is free of your code it consumes the messages and your app comes alive again.

Caius Jard
  • 72,509
  • 5
  • 49
  • 80