简体   繁体   English

如何在C#中创建一个长时间运行的进程?

[英]How would I create a long running process in C#?

This may seem very elementary, but I don't really have any experience in this realm - all my experience has been on the web side of things. 这可能看起来非常基础,但我在这个领域没有任何经验 - 我所有的经验都是在网络方面。

I need to create a process of some sort that will repeatedly query an API (around 5 times a second), get the results from the API (in JSON format), and then my process will do what it needs to do with the results (in my case, insert them into a SQL database). 我需要创建一个将重复查询API(大约每秒5次),从API(以JSON格式)获取结果的某种流程,然后我的流程将执行它对结果所需的操作(在我的例子中,将它们插入SQL数据库)。 These details don't really matter to the scope of the question I have, I just want to give you an idea on what I'm trying to achieve in case someone wants to recommend a better way of doing it. 这些细节对我的问题的范围并不重要,我只是想让你了解我想要实现的目标,以防有人想要推荐更好的方法。

My first thought was to create a console app that basically never quits (unless I specifically tell it to). 我的第一个想法是创建一个基本上永不退出的控制台应用程序(除非我明确告诉它)。 Is a console app the way to go for this? 控制台应用程序是这样的吗? The idea is I'll have a VM set up which will host my solution, including this "process" I create. 我的想法是我将设置一个VM来托管我的解决方案,包括我创建的这个“过程”。 I'm not all too familiar with Windows Services, or Windows Tasks, but I probably need to write some custom code so therefore I imagine I can't use the Windows Task Scheduler, am I right? 我不太熟悉Windows服务或Windows任务,但我可能需要编写一些自定义代码,因此我想我不能使用Windows任务计划程序,我是对的吗?

Once options would be to create a Windows Service which is the OS-level implementation of a long running process . 一旦选项将创建一个Windows服务,这是一个长期运行的进程的操作系统级实现。 To do so in C# you may wish to read through some tutorials online, perhaps starting with the MSDN Walkthrough . 要在C#中这样做,您可能希望在线阅读一些教程,可能从MSDN演练开始 You should also read about Windows Services in general and the differences between a service and a regular user process (mainly the fact that services have no UI and can't interact with the user directly, and some of the other security considerations). 您还应该了解一般的Windows服务以及服务和常规用户进程之间的差异(主要是服务没有UI且无法直接与用户交互的事实,以及其他一些安全注意事项)。

Other options may be to leverage a framework such as WCF or similar. 其他选项可能是利用诸如WCF或类似的框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM