user2997958
user2997958

Reputation: 11

Where to add a polling function to a form?

Using C#, Visual Studio 2010, windows 7....

I have a form with an OvalShape. I want to add this function to the form thread or make a background thread that checks a service's status and changes the color of the OvalShape like a traffic light.

private void ServiceStatus()
{
  if (ServiceManagement.ServiceStatus("OracleServiceXE"))
     ovalshape.BackColor =Color.Green;
  else
     ovalshape.BackColor = Color.Red;

}

Where is best spot to add this functionality to be constantly (every 1-5 seconds) executing?

Upvotes: 0

Views: 690

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

Does ServiceManagement.ServiceStatus() always return quickly? If the service status is false, is there a delay in returning that information?

If yes, then you don't want that line running in the main UI thread via a Timer as it may render your app un-responsive.

If this is a possibility, then a secondary thread might be warranted. The BackgroundWorker() control could be one approach:

public partial class Form1 : Form
{

    private BackgroundWorker bgw = new BackgroundWorker();

    public Form1()
    {
        InitializeComponent();
        bgw.WorkerReportsProgress = true;
        bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
        bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
    }

    private void bgw_DoWork(object sender, DoWorkEventArgs e)
    {
        while (true)
        {
            if (ServiceManagement.ServiceStatus("OracleServiceXE"))
            {
                bgw.ReportProgress(-1, Color.Green);
            }
            else
            {
                bgw.ReportProgress(-1, Color.Red);
            }
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
        }
    }

    private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        ovalshape.BackColor = (Color)e.UserState;
    }

}

Upvotes: 1

Thomas Weller
Thomas Weller

Reputation: 59208

WinForms: drag a Timer onto the form, set Enabled to true and Interval to 5000. Double click the timer to add the Tick-Eventhandler. From there, run your method.

WPF:

using System.Timers;
Timer serviceStatusTimer = new Timer(5000);
private void OnLoaded(object sender, RoutedEventArgs e) // Window loaded event
{
    serviceStatusTimer.Elapsed += ServiceStatus;
    serviceStatusTimer.Enabled = true;
    serviceStatusTimer.Start();
}

Upvotes: 0

Related Questions