Reputation: 122
namespace Client
{
class Program
{
static TcpClient client = new TcpClient();
static bool isServerOn = false;
static void Main(string[] args)
{
Timer timer = new Timer(1000);
timer.Elapsed += Update;
timer.Enabled = true;
}
private static void Update(Object source, ElapsedEventArgs e)
{
try
{
client.Connect("127.0.0.1", 1233);
if (isServerOn) return;
isServerOn = true;
Console.WriteLine("Server is On");
} catch(Exception)
{
if (!isServerOn) return;
isServerOn = false;
Console.WriteLine("Server Is Off");
}
}
}
}
i got this code for my client and the timer dont run because the application close after i run it can someone tell me how to make the timer run and the application dont close at the same time
Upvotes: 2
Views: 1438
Reputation: 513
You can solve this using Tasks.
Try this or something like it:
static void Main(string[] args)
{
Task t = Task.Run(async () => {
do
{
Update();
await Task.Delay(1000);
} while (isServerOn);
});
t.Wait();
}
Upvotes: 4
Reputation: 77866
Well you can use a Console.ReadKey()
or Console.ReadLine()
method like below but you should actually make it a WindowsService application rather a normal console application
static void Main(string[] args)
{
Timer timer = new Timer(1000);
timer.Elapsed += Update;
timer.Enabled = true;
Console.ReadKey();
}
Upvotes: 5