|
| 1 | +using BlazorWorker.Core; |
| 2 | +using BlazorWorker.WorkerCore; |
| 3 | +using System; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using BlazorWorker.BackgroundServiceFactory; |
| 6 | +using Microsoft.JSInterop; |
| 7 | +using BlazorWorker.WorkerBackgroundService; |
| 8 | +using System.Runtime.InteropServices.JavaScript; |
| 9 | + |
| 10 | +namespace BlazorWorker.Demo.Shared |
| 11 | +{ |
| 12 | + public partial class JsDirectExample |
| 13 | + { |
| 14 | + private readonly IWorkerFactory workerFactory; |
| 15 | + private readonly IJSRuntime jsRuntime; |
| 16 | + private IWorkerBackgroundService<JsDirectExampleWorkerService> service; |
| 17 | + private long workerId; |
| 18 | + public event EventHandler<string> LogHandler; |
| 19 | + |
| 20 | + public JsDirectExample(IWorkerFactory workerFactory, IJSRuntime jsRuntime) |
| 21 | + { |
| 22 | + this.workerFactory = workerFactory; |
| 23 | + this.jsRuntime = jsRuntime; |
| 24 | + } |
| 25 | + |
| 26 | + private void Log(string message) |
| 27 | + { |
| 28 | + LogHandler?.Invoke(this, message); |
| 29 | + } |
| 30 | + |
| 31 | + public async Task Execute() |
| 32 | + { |
| 33 | + if (this.service == null) |
| 34 | + { |
| 35 | + Log("Execute: Creating worker..."); |
| 36 | + var worker = await this.workerFactory.CreateAsync(); |
| 37 | + this.workerId = worker.Identifier; |
| 38 | + Log("Execute: Creating service..."); |
| 39 | + this.service = await worker.CreateBackgroundServiceAsync<JsDirectExampleWorkerService>(); |
| 40 | + |
| 41 | + Log("Execute: Setting up main js..."); |
| 42 | + |
| 43 | + // Method setupJsDirectForWorker is defined in BlazorWorker.Demo.SharedPages/wwwroot/JsDirectExample.js |
| 44 | + await this.jsRuntime.InvokeVoidAsync("setupJsDirectForWorker", this.workerId); |
| 45 | + } |
| 46 | + |
| 47 | + Log("Execute: Calling ExecuteJsDirect on worker..."); |
| 48 | + await service.RunAsync(s => s.ExecuteJsDirect()); |
| 49 | + Log("Execute: Done"); |
| 50 | + } |
| 51 | + |
| 52 | + } |
| 53 | + |
| 54 | + public class JsDirectExampleWorkerService |
| 55 | + { |
| 56 | + private readonly IWorkerMessageService messageService; |
| 57 | + public JsDirectExampleWorkerService(IWorkerMessageService messageService) |
| 58 | + { |
| 59 | + this.messageService = messageService; |
| 60 | + } |
| 61 | + public async Task ExecuteJsDirect() |
| 62 | + { |
| 63 | + await messageService.PostMessageJsDirectAsync("Hello main js thread."); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments