-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackgroundWorker.cs
74 lines (61 loc) · 2.39 KB
/
BackgroundWorker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Hosting;
using System.Diagnostics;
using System.Text.Json;
namespace isolatedWorkerSignalr;
public class BackgroundWorker : BackgroundService
{
private HubConnection? _connection;
private readonly HttpClient _httpClient;
public BackgroundWorker(IHttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory.CreateClient("function-api");
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
var negotiateMessage = new HttpRequestMessage(HttpMethod.Get, "api/negotiate");
var response = _httpClient.Send(negotiateMessage, cancellationToken);
var info = JsonSerializer.Deserialize<SignalRConnectionInfo>(response.Content.ReadAsStream(cancellationToken)) ?? new();
_connection = new HubConnectionBuilder()
.WithUrl(info.Url, (options) =>
{
options.AccessTokenProvider = () => Task.FromResult((string?)info.AccessToken);
})
.Build();
_connection.On<string>("method1", (message) =>
{
Console.WriteLine($"Client received message from hub: {message}");
});
await _connection.StartAsync(cancellationToken);
await base.StartAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
await NotifyViaHttp(stoppingToken);
await NotifyViaSignalR(stoppingToken);
}
}
catch (Exception ex)
{
Debug.Assert(true);
Console.WriteLine(ex.Message);
}
}
private async Task NotifyViaHttp(CancellationToken stoppingToken)
{
Console.WriteLine("Client notifying hub to broadcast via http.");
var request = new HttpRequestMessage(HttpMethod.Get, "api/broadcast-message");
await _httpClient!.SendAsync(request, stoppingToken);
}
private async Task NotifyViaSignalR(CancellationToken stoppingToken)
{
Console.WriteLine("Client notifying hub to broadcast via signalR.");
await _connection!.InvokeAsync("method2", stoppingToken);
}
}