Tvd
Tvd

Reputation: 4601

REG Threading: How to implement This

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.

I read the 2-3 tutorials, but can't make out how to implement this - which thread type or so to use and call.

Implemented Code of Form :

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){    
    if (currentState == OPENING)
         LoadAfterLogin();
    else if (currentState == CONNECTING)
         Connect();    // CONNECTS TO THE SERVER
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e){
    ......   
    else if (value == CONNECTED)   {
        currentState = CONNECTED;
        statusLabel.Text = "CONNECTED Successfully to server";
       //  HERE MONITOR THREAD SHOULD BE STARTED ONCE APP KNOWS FOR SURE, THAT IT IS CONNECTED 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; }
}

// SHOULD CALL THIS WHEN THE THREAD IS STARTED
public void start()    {
    startTime = DateTime.Now;
    nextTime = DateTime.Now;
}

// THIS SHOULD BE SOMEHOW CALLED BY run()
public void checkConnection()    { 
   // IS CURRENT TIME IS >= SCHEDULED NEXTTIME
    if (DateTime.Now >= nextTime) {
        // Checks if the connection to server is alive or not
        conneced = UltimateLibrary.http.HTTPUtility.isConnectionAvailable();
        lastCheckedTime = DateTime.Now;
        nextTime = lastCheckedTime + intervalDuration;
    }
}

// SOMETHING LIKE RUN - that starts the process execution
public void run() {
   while (true) {
        if (DateTime.Now >= nextTime)
            checkConnection();
        Thread.sleep(interval); 
   }
}

}

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. Can anyone please give me some hint/idea to implement the above.

[EDITED:] Thanks Vinay, Based on your code, I implemented as follows :- Created a Timer obj in MonitorConnection class.

        public void StartMonitor()
        {
            startTime = DateTime.Now;
            nextTime = DateTime.Now;
            timer = new Timer(intervalDuration);
            timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            GC.KeepAlive(timer);    // I don't think this is reqd as timer is a member of class
            timer.Start();   // Can also call timer.Enabled = true;
        }

    public static void checkConnection()
    {
        if (DateTime.Now >= nextTime) {
            // Checks if the connection to server is alive or not
            connected = UltimateLibrary.http.HTTPUtility.isConnectionAvailable();
            lastCheckedTime = DateTime.Now;
            nextTime = lastCheckedTime.AddMilliseconds(intervalDuration);
        }

    }

    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        // Check if connection is alive
        checkConnection();
    }

. If the connected is false i.e. server is not connected, then have to let the calling form know about that. I guess for that can pass an object of form to this class and call its respective method when connected == false. What do you say ? Is this and the above code seems to be proper ? Your guidance is and will be highly appreciated. - Thanks

Thanks

Upvotes: 1

Views: 115

Answers (1)

VinayC
VinayC

Reputation: 49245

Why not use Timer for this - its quite simple to use. For example,

    public event EventHandler Disconnected;


    timer = new System.Timers.Timer(10000);
    timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    timer.Enabled = true;

    ...

    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
       // check if connection is alive
       conneced = UltimateLibrary.http.HTTPUtility.isConnectionAvailable();
       if (!connected)
       { 
          // inform listeners
          var listener = Disconnected;
          if (null !- listener)
          {
              Disconnected(EventArgs.Empty);
          }
       }
    }

Only care that you must take to make sure that timer is referenced for required duration (otherwise it would be garbage collected).

Upvotes: 0

Related Questions