From 549b83157734a7c9619f20290c432b3cd20f49e9 Mon Sep 17 00:00:00 2001 From: Paulo Rogerio Panhoto Date: Thu, 22 Feb 2018 11:12:32 -0300 Subject: [PATCH] Instead of relying on a cancellation token, which caused some confusion on client implementation, Loop will run within constrained intervals which will be the longer waiting period for a scheduled action to run. --- TLSharp.Core/Network/MtProtoSender.cs | 4 ++-- TLSharp.Core/Network/TcpTransport.cs | 8 ++++++-- TLSharp.Core/TelegramClient.cs | 10 +++++----- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/TLSharp.Core/Network/MtProtoSender.cs b/TLSharp.Core/Network/MtProtoSender.cs index 1884f47..54a9665 100644 --- a/TLSharp.Core/Network/MtProtoSender.cs +++ b/TLSharp.Core/Network/MtProtoSender.cs @@ -159,9 +159,9 @@ namespace TLSharp.Core.Network return null; } - public async Task Receive(CancellationToken token) + public async Task Receive(int timeoutms) { - var result = DecodeMessage ((await _transport.Receieve (token)).Body); + var result = DecodeMessage ((await _transport.Receieve (timeoutms)).Body); using (var messageStream = new MemoryStream (result.Item1, false)) using (var messageReader = new BinaryReader (messageStream)) diff --git a/TLSharp.Core/Network/TcpTransport.cs b/TLSharp.Core/Network/TcpTransport.cs index 39ae672..83d5038 100644 --- a/TLSharp.Core/Network/TcpTransport.cs +++ b/TLSharp.Core/Network/TcpTransport.cs @@ -87,12 +87,16 @@ namespace TLSharp.Core.Network return new TcpMessage(seq, body); } - public async Task Receieve(CancellationToken token) + public async Task Receieve(int timeoutms) { var stream = _tcpClient.GetStream(); var packetLengthBytes = new byte[4]; - if (await stream.ReadAsync(packetLengthBytes, 0, 4, token) != 4) + var recvTask = stream.ReadAsync(packetLengthBytes, 0, 4); + var task = await Task.WhenAny(recvTask, Task.Delay(timeoutms)); + if (task != recvTask) + throw new TimeoutException(); + if (recvTask.Result != 4) throw new InvalidOperationException("Couldn't read the packet length"); int packetLength = BitConverter.ToInt32(packetLengthBytes, 0); diff --git a/TLSharp.Core/TelegramClient.cs b/TLSharp.Core/TelegramClient.cs index c898598..b9aebb5 100644 --- a/TLSharp.Core/TelegramClient.cs +++ b/TLSharp.Core/TelegramClient.cs @@ -117,15 +117,15 @@ namespace TLSharp.Core } } - public async Task MainLoopAsync(CancellationTokenSource source) + public async Task MainLoopAsync(int timeslicems) { for (;;) { try { logger.Trace("Socket waiting"); - await WaitEventAsync(source.Token); - } catch (OperationCanceledException) + await WaitEventAsync(timeslicems); + } catch (TimeoutException) { } finally @@ -162,9 +162,9 @@ namespace TLSharp.Core } } - public async Task WaitEventAsync(CancellationToken token) + public async Task WaitEventAsync(int timeoutms) { - await _sender.Receive (token); + await _sender.Receive (timeoutms); } public bool IsUserAuthorized()