Blazor Webassembly 应用程序中的轮询线程
Polling Thread in a Blazor Webassembly App
我的问题与 类似,但不是关于 Blazor 服务器 应用程序,而是在 Blazor 的上下文中提问]webassembly 应用程序。我意识到在这个浏览器执行上下文中只有一个 (UI) 线程,但我认为必须有某种用于工作程序或后台服务的框架。我所有的谷歌搜索都是空的。
我只需要启动一个后台服务,在应用程序的生命周期内每秒持续轮询 Web API。
我看到了两种不同的方法。第一个是 AppCompontent
中的简单 timer-based 调用。第二种是创建一个 javascript web worker 并通过互操作调用它。
Timer-based 在 App
组件
@inject HttpClient client
@implements IDisposable
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
@code {
private async void DoPeriodicCall(Object state)
{
//a better version can found here https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#timer-callbacks
var response = await client.GetFromJsonAsync<Boolean>("something here");
//Call a service, fire an event to inform components, etc
}
private System.Threading.Timer _timer;
protected override void OnInitialized()
{
base.OnInitialized();
_timer = new System.Threading.Timer(DoPeriodicCall, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
public void Dispose()
{
//maybe to a "final" call
_timer.Dispose();
}
}
Javascript 网络工作者
可以找到后台工作者的一个很好的起点here。
如果你想在你的 WASM 应用程序中使用调用的结果,你需要实现 JS 互操作。 App
组件调用 javascript 方法来启动 worker。 javascript 方法有三个输入,URL、区间和对 App
组件的引用。 URL 和间隔包含在“cmd”object 中,并在工作人员启动时传递给工作人员。当 worker 完成 API 调用时,它会向 javascript 返回一条消息。 javascript 调用应用程序组件上的一个方法。
// js/apicaller.js
let timerId;
self.addEventListener('message', e => {
if (e.data.cmd == 'start') {
let url = e.data.url;
let interval = e.data.interval;
timerId = setInterval( () => {
fetch(url).then(res => {
if (res.ok) {
res.json().then((result) => {
self.postMessage(result);
});
} else {
throw new Error('error with server');
}
}).catch(err => {
self.postMessage(err.message);
})
}, interval);
} else if(e.data.cmd == 'stop') {
clearInterval(timerId);
}
});
// js/apicaller.js
window.apiCaller = {};
window.apiCaller.worker = new Worker('/js/apicallerworker.js');
window.apiCaller.workerStarted = false;
window.apiCaller.start = function (url, interval, dotNetObjectReference) {
if (window.apiCaller.workerStarted == true) {
return;
}
window.apiCaller.worker.postMessage({ cmd: 'start', url: url, interval: interval });
window.apiCaller.worker.onmessage = (e) => {
dotNetObjectReference.invokeMethodAsync('HandleInterval', e.data);
}
window.apiCaller.workerStarted = true;
}
window.apiCaller.end = function () {
window.apiCaller.worker.postMessage({ cmd: 'stop' });
}
您需要修改 index.html 以引用 apicaller.js 脚本。我建议在 blazor 框架之前包含它,以确保它之前可用。
...
<script src="js/apicaller.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
...
app组件需要稍微修改一下。
@implements IAsyncDisposable
@inject IJSRuntime JSRuntime
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
@code {
private DotNetObjectReference<App> _selfReference;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
_selfReference = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("apiCaller.start", "/sample-data/weather.json", 1000, _selfReference);
}
}
[JSInvokable("HandleInterval")]
public void ServiceCalled(WeatherForecast[] forecasts)
{
//Call a service, fire an event to inform components, etc
}
public async ValueTask DisposeAsync()
{
await JSRuntime.InvokeVoidAsync("apiCaller.stop");
_selfReference.Dispose();
}
}
在开发人员工具中,您可以看到一个工作人员在执行调用。
并发、多线程等问题
worker 是一种真正的多线程方法。线程池由浏览器处理。 worker 中的调用不会阻塞“主”线程中的任何语句。但是,它不如第一种方法方便。选择什么方法取决于您的上下文。只要您的 Blazor 应用程序不会执行太多操作,第一种方法可能是一个合理的选择。如果您的 Blazor 应用程序已经有大量的事情要做,卸载给工作人员可能会非常有益。
如果您寻求工作者解决方案,但需要一个 non-default 客户端,例如带有身份验证或特殊 headers,您将需要找到一种机制来同步 Blazor HttpClient
和调用 fetch
API.
我的问题与
我只需要启动一个后台服务,在应用程序的生命周期内每秒持续轮询 Web API。
我看到了两种不同的方法。第一个是 AppCompontent
中的简单 timer-based 调用。第二种是创建一个 javascript web worker 并通过互操作调用它。
Timer-based 在 App
组件
@inject HttpClient client
@implements IDisposable
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
@code {
private async void DoPeriodicCall(Object state)
{
//a better version can found here https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#timer-callbacks
var response = await client.GetFromJsonAsync<Boolean>("something here");
//Call a service, fire an event to inform components, etc
}
private System.Threading.Timer _timer;
protected override void OnInitialized()
{
base.OnInitialized();
_timer = new System.Threading.Timer(DoPeriodicCall, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
public void Dispose()
{
//maybe to a "final" call
_timer.Dispose();
}
}
Javascript 网络工作者
可以找到后台工作者的一个很好的起点here。
如果你想在你的 WASM 应用程序中使用调用的结果,你需要实现 JS 互操作。 App
组件调用 javascript 方法来启动 worker。 javascript 方法有三个输入,URL、区间和对 App
组件的引用。 URL 和间隔包含在“cmd”object 中,并在工作人员启动时传递给工作人员。当 worker 完成 API 调用时,它会向 javascript 返回一条消息。 javascript 调用应用程序组件上的一个方法。
// js/apicaller.js
let timerId;
self.addEventListener('message', e => {
if (e.data.cmd == 'start') {
let url = e.data.url;
let interval = e.data.interval;
timerId = setInterval( () => {
fetch(url).then(res => {
if (res.ok) {
res.json().then((result) => {
self.postMessage(result);
});
} else {
throw new Error('error with server');
}
}).catch(err => {
self.postMessage(err.message);
})
}, interval);
} else if(e.data.cmd == 'stop') {
clearInterval(timerId);
}
});
// js/apicaller.js
window.apiCaller = {};
window.apiCaller.worker = new Worker('/js/apicallerworker.js');
window.apiCaller.workerStarted = false;
window.apiCaller.start = function (url, interval, dotNetObjectReference) {
if (window.apiCaller.workerStarted == true) {
return;
}
window.apiCaller.worker.postMessage({ cmd: 'start', url: url, interval: interval });
window.apiCaller.worker.onmessage = (e) => {
dotNetObjectReference.invokeMethodAsync('HandleInterval', e.data);
}
window.apiCaller.workerStarted = true;
}
window.apiCaller.end = function () {
window.apiCaller.worker.postMessage({ cmd: 'stop' });
}
您需要修改 index.html 以引用 apicaller.js 脚本。我建议在 blazor 框架之前包含它,以确保它之前可用。
...
<script src="js/apicaller.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
...
app组件需要稍微修改一下。
@implements IAsyncDisposable
@inject IJSRuntime JSRuntime
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
@code {
private DotNetObjectReference<App> _selfReference;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
_selfReference = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("apiCaller.start", "/sample-data/weather.json", 1000, _selfReference);
}
}
[JSInvokable("HandleInterval")]
public void ServiceCalled(WeatherForecast[] forecasts)
{
//Call a service, fire an event to inform components, etc
}
public async ValueTask DisposeAsync()
{
await JSRuntime.InvokeVoidAsync("apiCaller.stop");
_selfReference.Dispose();
}
}
在开发人员工具中,您可以看到一个工作人员在执行调用。
并发、多线程等问题
worker 是一种真正的多线程方法。线程池由浏览器处理。 worker 中的调用不会阻塞“主”线程中的任何语句。但是,它不如第一种方法方便。选择什么方法取决于您的上下文。只要您的 Blazor 应用程序不会执行太多操作,第一种方法可能是一个合理的选择。如果您的 Blazor 应用程序已经有大量的事情要做,卸载给工作人员可能会非常有益。
如果您寻求工作者解决方案,但需要一个 non-default 客户端,例如带有身份验证或特殊 headers,您将需要找到一种机制来同步 Blazor HttpClient
和调用 fetch
API.