I have a C# program to check if a hard coded host is available and if not, waits then checks again (this is a loop in form of recursion). How can it be enhanced?
using System;
using System.Net.NetworkInformation;
using System.Windows.Forms;
namespace trial17
{
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
}
static Ping p = new Ping();
static string host = "8.8.8.8";
static byte[] buffer = new byte[32];
static int timeout = 1000;
static PingOptions po = new PingOptions();
static PingReply pr;
static bool load = false;
//plays media if connected
System.Media.SoundPlayer player = new System.Media.SoundPlayer("media file path");
private void Form5_Load(object sender, EventArgs e)
{
try
{
Show();
conn();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
async void conn()
{
try
{
pr = p.Send(host, timeout, buffer, po);
if (pr.Status == IPStatus.Success)
{
player.Play();
//label updated after connection
label1.Text = "Connected";
}
else
{
await System.Threading.Tasks.Task.Delay(200);
conn();
}
}
catch (Exception) {
}
}
}
}
1 Answer 1
You probably want to avoid using recursion on conn
. Say you did not have internet connection for a long time. Then, for every failed connection you will add a new entry to the call stack. Which could eventually lead to a stack overflow.
It's probably a better idea to have two methods. Something along the lines of:
// Ignoring exception handling for sake of simplicity
bool checkConnection()
{
pr = p.Send(host, timeout, buffer, po);
return pr.Status == IPStatus.Success;
}
async void connectionTask()
{
while (!checkConnection())
{
await System.Threading.Tasks.Task.Delay(200);
}
player.Play();
//label updated after connection
label1.Text = "Connected";
}
-
\$\begingroup\$ Is the
Task.Delay()
method capable of causing a Stack Overflow? And how long should my optimal delay time in ms be? \$\endgroup\$user14773854– user147738542021年06月12日 17:00:08 +00:00Commented Jun 12, 2021 at 17:00 -
\$\begingroup\$ avoid
async void
. \$\endgroup\$aepot– aepot2021年06月12日 22:26:55 +00:00Commented Jun 12, 2021 at 22:26 -
\$\begingroup\$ @aepot I tried running this program for 10 minutes and it caused a BSOD with an error regarding unchecked kernel. What happened? \$\endgroup\$user14773854– user147738542021年06月27日 17:26:30 +00:00Commented Jun 27, 2021 at 17:26
-
\$\begingroup\$ @user14773854 C# can't cause OS kernel fault because it's managed code. Probably there's some drivers or hardware issue. \$\endgroup\$aepot– aepot2021年06月27日 17:41:00 +00:00Commented Jun 27, 2021 at 17:41