This repository was archived by the owner on Feb 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExtensions.cs
More file actions
86 lines (76 loc) · 2.91 KB
/
Extensions.cs
File metadata and controls
86 lines (76 loc) · 2.91 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Nodebridge
{
public static class Bridgextensions
{
/// <summary>
/// Add the bridge to DI
/// </summary>
/// <param name="serviceCollection"></param>
/// <param name="options"></param>
/// <returns>IServiceCollection</returns>
public static IServiceCollection AddNodeBridge(this IServiceCollection serviceCollection, Action<InvokeOptions> options = null)
{
serviceCollection.AddSingleton(typeof(Bridge), serviceProvider =>
{
var config = new InvokeOptions();
var lifetime = serviceProvider.GetService<IHostApplicationLifetime>();
if (options != null)
{
options.Invoke(config);
}
CancellationToken stoppingToken;
// Get current logger if none was supplied.
if (config.Logger == null)
{
var factory = serviceProvider.GetService<ILoggerFactory>();
config.Logger = factory.CreateLogger<Bridge>();
}
if (lifetime != null)
{
stoppingToken = lifetime.ApplicationStopping;
}
return new Bridge(config, stoppingToken);
});
return serviceCollection;
}
/// <summary>
/// make ReadAsStringAsync cancellable.
/// </summary>
/// <param name="task"></param>
/// <param name="cancellationToken"></param>
/// <returns>Task</returns>
internal static Task WithCancellation(this Task task, CancellationToken cancellationToken)
{
return task.IsCompleted
? task
: task.ContinueWith(
completedTask => completedTask.GetAwaiter().GetResult(),
cancellationToken,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
/// <summary>
/// make ReadAsStringAsync cancellable.
/// </summary>
/// <param name="task"></param>
/// <param name="cancellationToken"></param>
/// <typeparam name="T"></typeparam>
/// <returns>Task<T></returns>
internal static Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
{
return task.IsCompleted
? task
: task.ContinueWith(
completedTask => completedTask.GetAwaiter().GetResult(),
cancellationToken,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
}
}