Skip to content

Instantly share code, notes, and snippets.

View neuecc's full-sized avatar

Yoshifumi Kawai neuecc

View GitHub Profile
class Client
{
// For classes that prohibit multiple calls to methods such as SqlConnection, add a single CancellationTokenSource to the field
// Things like HttpClient, which may be called multiple times, are held in ObjectPool.
readonly ObjectPool<CancellationTokenSource> timeoutTokenSourcePool;
public TimeSpan Timeout { get; }
public Client(TimeSpan timeout)
public async Task SendAsync(CancellationToken cancellationToken = default)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(Timeout);
try
{
await SendCoreAsync(cts.Token);
}
catch (OperationCanceledException ex) when (ex.CancellationToken == cts.Token)
try
{
await client.SendAsync(token);
}
catch (OperationCanceledException ex) when (ex.CancellationToken == token)
{
// detect reason of Cancel by Token
}
class Client
{
public TimeSpan Timeout { get; }
public Client(TimeSpan timeout)
{
this.Timeout = timeout;
}
public async Task SendAsync(CancellationToken cancellationToken = default)
// Dispose will stop internal timer to prevent timer leak
using var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromMinutes(1));
await client.SendAsync(cts.Token);
class Client
{
public async Task SendAsync(CancellationToken cancellationToken = default)
{
await SendCoreAsync(cancellationToken);
}
async Task SendCoreAsync(CancellationToken cancellationToken)
{
// do anything...
public interface INatsSerializer
{
int Serialize<T>(ICountableBufferWriter bufferWriter, T? value);
T? Deserialize<T>(in ReadOnlySequence<byte> buffer);
}
public interface ICountableBufferWriter : IBufferWriter<byte>
{
int WrittenCount { get; }
}
class AsyncPublishCommand<T> :
ICommand,
IValueTaskSource,
IThreadPoolWorkItem,
IObjectPoolNode<AsyncPublishCommand<T>>
internal interface ICommand
{
void Write(ProtocolWriter writer);
}
await connection.PublishAsync(value);
internal static class ServerOpCodes
{
public const int Info = 1330007625; // Encoding.ASCII.GetBytes("INFO") |> MemoryMarshal.Read<int>
public const int Msg = 541545293; // Encoding.ASCII.GetBytes("MSG ") |> MemoryMarshal.Read<int>
public const int Ping = 1196312912; // Encoding.ASCII.GetBytes("PING") |> MemoryMarshal.Read<int>
public const int Pong = 1196314448; // Encoding.ASCII.GetBytes("PONG") |> MemoryMarshal.Read<int>
public const int Ok = 223039275; // Encoding.ASCII.GetBytes("+OK\r") |> MemoryMarshal.Read<int>
public const int Error = 1381123373; // Encoding.ASCII.GetBytes("-ERR") |> MemoryMarshal.Read<int>
}