Add timeout option to JRPC-Api

This commit is contained in:
Fabian Stamm
2024-09-27 08:39:00 +02:00
parent fea830b295
commit 4465c62163
6 changed files with 79 additions and 15 deletions

View File

@ -1,9 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>10.0</LangVersion>
</PropertyGroup>
</Project>

View File

@ -11,10 +11,12 @@ public class JRpcClient
{
private JRpcTransport Transport;
private IDictionary<string, TaskCompletionSource<JsonNode?>> Requests;
private int? Timeout = null;
public JRpcClient(JRpcTransport transport)
public JRpcClient(JRpcTransport transport, int? timeout = null)
{
this.Transport = transport;
this.Timeout = timeout;
this.Requests = new Dictionary<string, TaskCompletionSource<JsonNode?>>();
this.Transport.OnPacket += this.HandlePacket;
@ -87,9 +89,28 @@ public class JRpcClient
var task = new TaskCompletionSource<JsonNode?>();
this.Requests.Add(id, task);
await this.Transport.Write(request.ToJsonString());
_ = Task.Run(async () =>
{
await this.Transport.Write(request.ToJsonString());
});
return await task.Task;
if (this.Timeout.HasValue)
{
if (await Task.WhenAny(task.Task, Task.Delay(this.Timeout.Value)) == task.Task)
{
return await task.Task;
}
else
{
this.Requests.Remove(id);
throw new JRpcException("Request Timeout");
}
}
else
{
return await task.Task;
}
}
public async Task<TResult?> SendRequest<TResult>(string method, JsonArray param)