Repository navigation
Expand file tree
/
Copy pathInstanceService.cs
More file actions
153 lines (144 loc) · 7.51 KB
/
Copy pathInstanceService.cs
File metadata and controls
153 lines (144 loc) · 7.51 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#nullable enable
using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace TrayChrome
{
public class InstanceResponse
{
public AppGroupEntry? Entry { get; set; }
public string? Error { get; set; }
public bool Ready { get; set; }
}
public sealed class InstanceService : IDisposable
{
private readonly Func<AppGroupEntry> snapshot;
private readonly Action close;
private readonly Func<bool> isReady;
private readonly Func<AppGroupEntry, Task> apply;
private readonly Action show;
private readonly CancellationTokenSource shutdown = new CancellationTokenSource();
public InstanceService(Func<AppGroupEntry> snapshot, Func<bool> isReady, Action close,
Func<AppGroupEntry, Task> apply, Action show)
{
this.snapshot = snapshot;
this.close = close;
this.isReady = isReady;
this.apply = apply;
this.show = show;
}
private static string PipeName(int id) => $"TrayChrome.Instance.{id}";
private const string ApplyPrefix = "apply ";
public static async Task<InstanceResponse> ApplyAsync(int id, AppGroupEntry entry)
{
// 新标签页初始化可能较慢,给应用配置更长的超时。
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(60));
return await RequestAsync(id, ApplyPrefix + JsonSerializer.Serialize(entry), timeout.Token);
}
public void Start() => _ = ServeAsync();
private async Task ServeAsync()
{
try
{
while (!shutdown.IsCancellationRequested)
{
using var pipe = new NamedPipeServerStream(PipeName(Environment.ProcessId), PipeDirection.InOut,
1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
await pipe.WaitForConnectionAsync(shutdown.Token);
using var requestTimeout = CancellationTokenSource.CreateLinkedTokenSource(shutdown.Token);
requestTimeout.CancelAfter(TimeSpan.FromSeconds(10));
using var reader = new StreamReader(pipe, Encoding.UTF8, false, 1024, true);
using var writer = new StreamWriter(pipe, new UTF8Encoding(false), 1024, true) { AutoFlush = true };
bool shouldClose = false;
var response = new InstanceResponse();
try
{
string? command = await reader.ReadLineAsync(requestTimeout.Token);
try
{
if (command != null && command.StartsWith(ApplyPrefix, StringComparison.Ordinal))
{
var entry = JsonSerializer.Deserialize<AppGroupEntry>(command.Substring(ApplyPrefix.Length))
?? throw new InvalidDataException("实例配置为空。");
await await Application.Current.Dispatcher.InvokeAsync(() => apply(entry));
response.Entry = await Application.Current.Dispatcher.InvokeAsync(snapshot);
}
else switch (command)
{
case "snapshot":
response.Entry = await Application.Current.Dispatcher.InvokeAsync(snapshot);
break;
case "close":
shouldClose = true;
break;
case "ping":
response.Ready = await Application.Current.Dispatcher.InvokeAsync(isReady);
break;
case "show":
await Application.Current.Dispatcher.InvokeAsync(show);
break;
default:
response.Error = "未知实例命令。";
break;
}
}
catch (Exception ex) when (ex is not IOException && ex is not OperationCanceledException)
{
response.Error = ex.Message;
}
// 应用配置可能需要创建标签页,写回响应单独计时。
using var writeTimeout = CancellationTokenSource.CreateLinkedTokenSource(shutdown.Token);
writeTimeout.CancelAfter(TimeSpan.FromSeconds(10));
await writer.WriteLineAsync(JsonSerializer.Serialize(response).AsMemory(), writeTimeout.Token);
}
catch (Exception ex) when (ex is IOException || ex is OperationCanceledException)
{
System.Diagnostics.Trace.WriteLine($"实例连接已中断: {ex.Message}");
continue;
}
if (shouldClose)
{
await Application.Current.Dispatcher.InvokeAsync(close);
return;
}
}
}
catch (OperationCanceledException) when (shutdown.IsCancellationRequested) { }
catch (Exception ex)
{
await Application.Current.Dispatcher.InvokeAsync(() =>
MessageBox.Show($"实例通信服务失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error));
}
}
public static async Task<InstanceResponse> RequestAsync(int id, string command, CancellationToken cancellationToken = default)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
if (!cancellationToken.CanBeCanceled) timeout.CancelAfter(TimeSpan.FromSeconds(5));
using var pipe = new NamedPipeClientStream(".", PipeName(id), PipeDirection.InOut,
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
try
{
await pipe.ConnectAsync(timeout.Token);
using var reader = new StreamReader(pipe, Encoding.UTF8, false, 1024, true);
using var writer = new StreamWriter(pipe, new UTF8Encoding(false), 1024, true) { AutoFlush = true };
await writer.WriteLineAsync(command.AsMemory(), timeout.Token);
string json = await reader.ReadLineAsync(timeout.Token)
?? throw new IOException("实例连接已关闭。");
var response = JsonSerializer.Deserialize<InstanceResponse>(json)
?? throw new InvalidDataException("实例响应为空。");
if (response.Error != null) throw new InvalidOperationException(response.Error);
return response;
}
catch (Exception ex) when (ex is IOException || ex is OperationCanceledException || ex is TimeoutException)
{
throw new IOException($"无法连接实例 {id},请确认所有实例均已更新至当前版本。", ex);
}
}
public void Dispose() => shutdown.Cancel();
}
}