Reputation: 3314
First, I apologize in advance if this is a duplicate question.
I wrote a windows service (c# .net 4.7) that creates a TcpClient connection to my alarm panel and listens for incoming data and then forwards the data to a website that I use to connect other services to. For reliability, I want to port this functionality to a c# MVC website so I can monitor it's state (make sure it's still connected, alarm hasn't gone off, etc).
I started out creating a MVC project & in the global.asax file, I kick off a new thread that loads/runs the class I originally created for the winService.
Application["MyTcpClass"] = new MyTcpClass();
Then in my HomeController, I added a Poll() ActionResult:
public void Poll()
{
MyTcpClass objClass = (MyTcpClass)Application["MyTcpClass"];
//If objClass is null, recreate/reconnect it
objClass.Poll();
}
Before I go any further and start adding a way to return statuses, etc, I wanted to check with everyone to see if this is a good method and/or if there's a better way?
Thanks in advance!
Upvotes: 0
Views: 948
Reputation: 40988
If you need to keep a custom TcpClient
open in the background, you're better off keeping it as a Windows service. ASP.NET will just complicate it.
For one (assuming you'll host it in IIS), IIS will, by default, shut off websites if they haven't gotten any incoming requests in 20 minutes. You can turn that behaviour off entirely, but it's still unreliable to expect IIS to keep your application running 100% of the time. Websites are designed to respond to HTTP requests, not to run background tasks.
If you want to make a website where you can check what your service is doing, then one way to do that is to use HttpListener
in your service to make a web service that your web application can call. I've done this before in a project I worked on. There's an example of how to use it here: https://www.codeproject.com/Articles/599978/An-HttpListener-Server-for-Handling-AJAX-POST-Requ
Update: I found that example too busy, so I created my own based on the past project I did: http://www.gabescode.com/dotnet/2018/11/01/basic-HttpListener-web-service.html
Upvotes: 3