Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4004858
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T08:19:27+00:00 2026-05-20T08:19:27+00:00

I have a Winform app that has a backgroundWorker thread and does all operations

  • 0

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T08:19:28+00:00Added an answer on May 20, 2026 at 8:19 am

    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).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a winform app that has tabcontrols that are 3 layers deep. I
I have a WinForm app that has other child forms (not mdi). If the
We have a winform app that has been in development for some time. It
I have a fairly large CRUD WinForm app that has numerous objects. Person, Enrollment,
Hopefully I am stating that right. I have a WinForm(3.5) app that has 1
I have a Winform app that has 16 SQL Connections currently stored in the
I have a C# winform app that has a tab control, I have a
I have a winform app that calls a web service to check for updates.
I have a web page that is being displaying in a winform app using
I have a Winform with a BackgroundWorker. The BackgroundWorker, among other things, has to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.