首页 > 解决方案 > Blazor Webassembly 应用程序中的轮询线程

问题描述

我的问题与类似,但不是与 Blazor服务器应用程序有关,而是在 Blazor webassembly应用程序的上下文中提问。我意识到这个浏览器执行上下文中只有一个(UI)线程,但我认为必须有某种框架用于工作人员或后台服务。我所有的谷歌搜索都是空的。

我只需要启动一个后台服务,该服务在应用程序的生命周期内每秒不断地轮询 Web API。

标签: blazor-webassembly

解决方案


我看到两种不同的方法。第一个是在您的AppCompontent. 第二种是创建一个 javascript web worker 并通过互操作调用它。

基于定时器的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 网络工作者

可以在这里找到后台工作人员的一个很好的起点。

如果你想在你的 WASM 应用中使用调用的结果,你需要实现 JS 互操作。该App组件调用启动工作程序的 javascript 方法。javascript 方法具有三个输入,即 URL、间隔和对App组件的引用。URL 和时间间隔被包装在一个“cmd”对象中,并在 worker 启动时传递给 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>
...
    

应用程序组件需要稍作修改。

@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 是一种真正的多线程方法。线程池由浏览器处理。工作线程内的调用不会阻塞“主”线程中的任何语句。但是,它不如第一种方法方便。选择哪种方法取决于您的上下文。只要您的 Blazor 应用程序不会做太多事情,第一种方法可能是一个合理的选择。如果您的 Blazor 应用程序已经有很多事情要做,那么卸载给工作人员可能会非常有益。

如果您选择工作人员解决方案,但需要一个非默认客户端(例如具有身份验证或特殊标头),则需要找到一种机制来同步 BlazorHttpClient和对fetchAPI 的调用。


推荐阅读