轮询 Web 服务 [英] Polling a web service

查看:24
本文介绍了轮询 Web 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C# 桌面 Windows 窗体应用程序.

I have a C# desktop Windows form application.

每 3 秒我就会调用一次网络服务,以检查服务器目录中的消息.

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

我有一个由线程启动的 while (true) 循环.在这个循环中调用 Web 服务.我知道我应该避免无限循环,但我不知道及时通知我的客户有新消息的简单方法.

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?

谢谢!

推荐答案

您可能可以为此使用 BackgroundWorker - 教程

You can probably use a BackgroundWorker for this - tutorial

您仍然需要使用 while(true) 循环,但您可以使用 BackgroundWorker 的 ReportProgress 方法与客户端进行通信:

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

然后为 DoWorkProgressChanged

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

这篇关于轮询 Web 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆