开发者

Developing a polling mechanism

In C#, what is the best way to create a polling mechanism? So I have some code which can periodically do some action.

This is for web services so any UI-related solutions won't apply.

Tha开发者_开发技巧nks


If you are saying that you have a web service which is supposed to periodically take some action on it's own, then I think you haven't quite got the web services model. Web services are supposed to sit there (just like a web page) until something kicks it off.

Otherwise you are dealing with a very brittle situation where anything could cause it to just stop.

If you have a bit of code that needs to run on a timer, then you should investigate placing that code in a windows service (not to be confused with Web Service). That's what they are for.


"code which can periodically do some action" is called a "Timer". Search MSDN, you'll find three or four classes for the purpose, several of which are non-gui (System.Threading.Timer comes to mind).

EDIT: To whom do the changes need to be visible? If they are only visible to other consumers of the web service, then one approach is for each incoming request can check whether a periodic action is overdue and perform it. However, you shouldn't do things this way if (1) the changes need to be visible to e.g. other clients of the same database, or (2) the periodic changes need greater permissions than arbitrary incoming requests. Also, the periodic actions might be interrupted if the client cancels their request, and doing the actions might significantly delay the response to the client. For these reasons I don't recommend adding periodic processing to normal request/response processing.


Take a look at the System.Threading.Timer class. This makes periodic calls to a method you supply. These calls are made on a separate thread (a thread in the thread pool).


You'll want to use a timer.

There are a few timers in the .NET framework, including:

  • System.Timers.Timer
  • System.Threading.Timer
  • System.Windows.Forms.Timer

See this article for help choosing the right one: Comparing the Timer Classes in the .NET Framework Class Library


It sounds like you want a Timer, but that does not make sense to use in a Web service. It would make more sense if the timer was in a client. What clients use your web service?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜