Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polling a web service

I have a C# desktop Windows form application.

Every 3 seconds I am invoking a call to a web service to check for messages in a directory on my server.

I have a while (true) loop, which was started by a thread. Inside this loop the call to the web service is made. I know I should avoid infinite loops, but I do not know an easy way of notifying my client of a new message in a timely fashion.

Are there alternatives I could look at please?

Thanks!

like image 475
Andrew Simpson Avatar asked Jun 07 '26 19:06

Andrew Simpson


1 Answers

You can probably use a BackgroundWorker for this - tutorial

You'd still need to use while(true) loop but you can communicate to the client by use the BackgroundWorker's ReportProgress Method:

// start the BackgroundWorker somewhere in your code:
DownloadDataWorker.RunWorkerAsync(); //DownloadDataWorker is the BackgroundWorker

then write the handlers for DoWork and ProgressChanged

private void DownloadRpdBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    while (true)
    {
        worker.ReportProgress(1);
        if (!controller.DownloadServerData())
        {
            worker.ReportProgress(2);
        }
        else
        {
            //data download succesful
            worker.ReportProgress(3);
        }
            System.Threading.Thread.Sleep(3000); //poll every 3 secs
    }
}

private void DownloadRpdBgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    switch(e.ProgressPercentage){
        case 1: SetStatus("Trying to fetch new data.."); break;
        case 2: SetStatus("Error communicating with the server"); break;
        case 3: SetStatus("Data downloaded!"); break;
    }
}
like image 161
Bethuel Rein Vendiola Avatar answered Jun 10 '26 17:06

Bethuel Rein Vendiola