Koden som den nye tråd udfører.
public int serverPort;
public string serverStatus;
public Color myColor;
public IPAddress serverIP;
private Socket mySocket;
public void check()
{
try
{
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
mySocket.Connect(serverIP, serverPort);
if (mySocket.Connected)
{
myColor = Color.DarkGreen;
serverStatus = "Online";
mySocket.Disconnect(true);
}
else
{
myColor = Color.DarkRed;
serverStatus = "Offline";
}
}
catch (SocketException)
{
}
finally
{
mySocket = null;
}
}
Functionen som starter tråd og opdaterer listview
private void timer1_Tick(object sender, EventArgs e)
{
Monitor myMonitor = new Monitor();
myMonitor.LoadServers();
listViewServers.Items.Clear();
toolStripProgressBarUpdate.Minimum = 0;
toolStripProgressBarUpdate.Maximum = myMonitor.Servers.Count;
toolStripProgressBarUpdate.Step = 1;
toolStripProgressBarUpdate.Value = 0;
for (int i = 0; i < myMonitor.Servers.Count; i++)
{
Server myServer = (Server)myMonitor.Servers[i];
myThread = new Thread(myMonitor.check);
myMonitor.serverIP = myServer.Ip;
myMonitor.serverPort = myServer.Port;
myThread.IsBackground = true;
myThread.Start();
ListViewItem myItem = new ListViewItem(myServer.Name);
myItem.ForeColor = myMonitor.myColor;
myItem.SubItems.Add(myServer.Ip.ToString());
myItem.SubItems.Add(myServer.Port.ToString());
myItem.SubItems.Add(myMonitor.serverStatus);
listViewServers.Items.Add(myItem);
listViewServers.Refresh();
toolStripProgressBarUpdate.PerformStep();
}
}