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

问题描述

我正在构建一个带有 REST API 和 Web 界面的 Blazor 应用程序.我还将拥有应用程序的一个监控部分,该部分将每秒轮询来自许多不同数据源的数据.我在一个单独的类中创建了一个长时间运行的线程,它只是轮询我想要的数据,它似乎工作正常.我使用的应用程序模板是 Blazor ASP.NET 服务器应用程序.就像这样:

I am building a Blazor application with a REST API and Web interface. I will also have a monitoring part of the application that will poll data each second from a lot of different data sources. I have created a long running thread in a separate class that simply polls the data I want and it seems to be working fine. The application template I am using is a Blazor ASP.NET Server application. Simply like this:

 m_pollThread = new Thread(new ThreadStart(PollThread))
 {
    IsBackground = true
 };
 m_pollThread.Start();

我现在想知道的是:将这种类型的轮询线程放在 Blazor 应用程序本身内部是否在编程模式方面完全错误?这样做是否有一些问题会在以后适得其反(内存消耗,应用程序其余部分的性能)?我之所以这么问,是因为据我所知,Blazor 和 ASP.NET Core 应用程序是一般的按需"应用程序,并在请求某些内容时唤醒,而不是执行长时间运行的无休止轮询任务.例如,我不知道我是否可以在 IIS 中运行它.

What I am wondering now is: is it completely wrong with respect to programming patterns to put this type of polling threads inside of the Blazor application itself? Is there some problems doing like this that will backfire later on (memory consumption, performance of the rest of the application)? The reason why I am asking is because as far as I know, Blazor and ASP.NET Core applications are general "on-request" and wakes up when something is requested, and not executing long-running endless polling tasks. I do not know if I could run that within IIS for instance.

推荐答案

是的.它不会立即打破,但它是在自找麻烦.

Yes. It won't break immediately but it is asking for trouble.

解决方案很简单,ASP.NET 核心让你运行 多个主机线程很容易.

The solution is easy though, ASP.NET core lets you run multiple Host threads very easily.

新的工作器模板现在可能是首选方式,但您真正需要的是

The new worker template is probably the preferred way now but all you really need is

class MyPollingService : BackgroundService { ... }

services.AddHostedService<MyPollingService>();

你的收获是更好地与框架集成,更好地控制启动和停止等.

Your gain is better integration with the framework and more control over Start and Stop etc.

这篇关于Blazor 中的轮询线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 16:24