Polling a web service

2019-07-15 08:21发布

问题:

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!

回答1:

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;
    }
}


回答2:

EDIT: Sorry for misreading. If you want to do something every 3 seconds, Use timers:

public static bool Stop = false;

public static void CheckEvery3Sec()
{
   System.Timers.Timer tm = new System.Timers.Timer(3000);
   tm.Start();
   tm.Elapsed += delegate
   {
       if (Stop)
       {
          tm.Stop();
          return;
       }
       ...
   };
}