Hello,
I have a Winform app that has a backgroundWorker thread and does all operations via that only.
After completing one particular operation i.e. to connect to the server, I want to create a monitor to check the connectivity with the server is alive or not. A web service will be executed to find out the connectivity and check the results to know. If not reconnect it. I believe I should create a thread for monitoring connectivity. The logic is like : After each X secs monitor checks the connectivity, again comes back after X secs and again does its job i.e check connectivity and know the status. I don't think their is any need to block the thread as I can react whenever I get the results. I also don't need to deal with any UI inside this process. Might only need once I find the connectivity is lost, then have to call for other function that reconnects and this thread again restarts or something like that.
To be very frank, I am week in Threading. I read the 2-3 tutorials, but can't make out how to implement this. Can anyone please give me some hint/idea to implement the above.
Implemented Code of Form :
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (currentState == OPENING)
LoadAfterLogin();
else if (currentState == CONNECTING)
Connect();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
......
else if (value == CONNECTED)
{
currentState = CONNECTED;
statusLabel.Text = "CONNECTED Successfully to server";
monitorConn = new MonitorConnection();
} else if (value == EXP)
{
currentState = ERR_CONNECTING;
ExceptionData ed = (ExceptionData)e.UserState;
.....
}
}
ANOTHER MonitorConnection thread class
public class MonitorConnection : Thread
{
private DateTime startTime, lastCheckedTime;
private bool conneced;
private int intervalDuration, nextTime;
public MonitorConnection()
{
intervalDuration = 10000;
}
public bool IsConneced
{
get { return conneced; }
set { conneced = value; }
}
public void start()
{
startTime = DateTime.Now;
nextTime = DateTime.Now;
}
public void checkConnection()
{
if (DateTime.Now >= nextTime) {
conneced = UltimateLibrary.http.HTTPUtility.isConnectionAvailable();
lastCheckedTime = DateTime.Now;
nextTime = lastCheckedTime + intervalDuration;
}
}
}
Here is the code that have implemetned to show the logic that I want to achieve. I agree and know the code is not fully to its mark. There still needs changes to make it proper by not blocking, running on continous intervals and so on. I think some other class than Thread should be extended (not sure which one will be appropriate).
Any help is highly appreciated.
Thanks