Reputation: 1814
I have a question, I have been following this post:
to build my background webserver. However, this post along with most that I read are just a headless background service. In my case, I do have a main app with a UI as well that the user can view and interact with. So, I am not headless, I want the app to start and show the UI when the device starts up. But, I also want a web server running in the background at all times (from within the app) to listen for JSON messages to be posted. For example, if I have text on the UI that I want to change by sending a JSON message to the device/app.
I understand that this is typically referred to as an in-process web server. So, I took most of the link above to implement the web server class and then from my MainPage.xaml.cs code behind, I did this to instantiate the web server class on another thread to listen for messages:
private async void StartServer()
{
var webServer = new WebServer();
await ThreadPool.RunAsync((workItem) =>
{
webServer.Start();
});
}
Is this the right way to start the web server in a background thread? As I read the code (and be easy on me, as I am still learning all of this stuff), it seems that the web service will start in the thread pool but then stop after it receives one message. Is that right or will it continue to run indefinitely (or as long as the app is running)?
Thanks!
Upvotes: 0
Views: 679
Reputation: 4432
Yes,it is a right way to start your web server in a background thread in headed UWP Application.In the thread pool,the web service will not stop after it receives messages,because the object of WebServer is not disposed.
Firstly, please refer to the Object Lifetime in .Net Framework.This topic is also about the life cycle of an object. The webServer object will not be disposed until the application exits.
Secondly, HTTP 1.1 implementa persistent connections.In the code you referred,each connection will be closed after web server responses to the client(web browser). So a separate TCP connection will be established to fetch each request in this web server.
var header = $"HTTP/1.1 200 OK\r\nContent-Length: {bodyStream.Length}\r\nConnection: close\r\n\r\n";
Upvotes: 2