Blazor Web assembly 应用程序中的轮询线程

BCA*_*BCA 3 blazor-webassembly

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

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

Jus*_*nno 8

我看到两种不同的方法。第一个是您的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();
    }
} 
Run Code Online (Sandbox Code Playgroud)

可以在开发者工具中观察到结果。 在此输入图像描述

JavaScript 网络工作者

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

如果您想在 WASM 应用程序中使用调用结果,则需要实现 JS 互操作。该App组件调用启动工作程序的 javascript 方法。javascript 方法具有三个输入:URL、间隔和对组件的引用App。URL 和间隔被包装在“cmd”对象内,并在工作进程启动时传递给工作进程。当工作线程完成 API 调用后,它会向 javascript 发送一条消息。此 JavaScript 调用应用程序组件上的方法。

@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();
    }
} 
Run Code Online (Sandbox Code Playgroud)

您需要修改index.html以引用apcaller.js脚本。我建议将其包含在 blazor 框架之前,以确保它之前可用。

// 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' });
}

Run Code Online (Sandbox Code Playgroud)

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

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在开发人员工具中,您可以看到工作人员执行调用。

在此输入图像描述

并发、多线程和其他问题

Worker 是一种真正的多线程方法。线程池由浏览器处理。工作线程内的调用不会阻塞“主”线程中的任何语句。但是,它不如第一种方法方便。选择什么方法取决于您的具体情况。只要您的 Blazor 应用程序不会做太多事情,第一种方法可能是一个合理的选择。如果您的 Blazor 应用程序已经有大量的事情要做,那么将其卸载给工作人员可能会非常有益。

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