Try this which uses a CheckBox to provide a valid and invalid check
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public delegate void OnStatusCheck(bool sender);
public static event OnStatusCheck StatusCheckEvent;
public Form1()
{
InitializeComponent();
StatusCheckEvent += OnStatusCheckEvent;
Shown += OnShown;
}
private void OnStatusCheckEvent(bool sender)
{
if (sender)
{
IsOnlineLabel.InvokeIfRequired(label => label.Text = "Online");
}
else
{
IsOnlineLabel.InvokeIfRequired(label => label.Text = "OffLine");
}
}
private void OnShown(object sender, EventArgs e)
{
var timer = new System.Timers.Timer {Interval = 500, Enabled = true};
timer.Elapsed += async (sender1, arguments) =>
await timer_Elapsed(sender1, arguments);
}
private async Task timer_Elapsed(object sender, ElapsedEventArgs arguments)
{
var url = _causeFailure ?
"http://theip/players.json" :
"https://stackoverflow.com/";
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
await request.GetResponseAsync();
StatusCheckEvent?.Invoke(true);
}
catch
{
StatusCheckEvent?.Invoke(false);
}
}
private bool _causeFailure;
private void CauseFailureCheckBox_CheckedChanged(object sender, EventArgs e)
{
_causeFailure = checkBox1.Checked;
}
}
public static class Extensions
{
public static void InvokeIfRequired<T>(this T control, Action<T> action) where T : ISynchronizeInvoke
{
if (control.InvokeRequired)
{
control.Invoke(new Action(() => action(control)), null);
}
else
{
action(control);
}
}
}
}