wiz0u / WTelegramClient

Telegram Client API (MTProto) library written 100% in C# and .NET
https://wiz0u.github.io/WTelegramClient/
MIT License
996 stars 164 forks source link

Add CancellationToken support for provided apis #139

Closed Kimi-Arthur closed 1 year ago

Kimi-Arthur commented 1 year ago

I seem to run into strange error where Task returned by SendMediaAsync won't finish, which is OK if the task can be properly canceled. But all these methods don't provide a CancellationToken parameter, which will be very helpful in such cases.

wiz0u commented 1 year ago
  1. I won't add a CancellationToken parameter to the methods because it makes no sense. Once you call an API, the request is immediately sent to Telegram servers, it's too late to "cancel" it and there is no way to ask Telegram to cancel the request, so even if it was possible, you wouldn't know if the request had been taken in account by Telegram servers or not.

  2. If you really need a way to bail out of a blocking task call, you can just use one of the task.WaitAsync(...) methods that creates a derived task, adding a CancellationToken or a timeout option to your task.

  3. And finally, I think you should investigate the root cause of your specific issue within your code, because under normal conditions, Telegram API calls shouldn't take much more than a few seconds (except in case of a FLOOD_WAIT where it can wait for up to 1 minute, depending on your client.FloodRetryThreshold settings). Maybe your task finished with an exception?

In any case, as a last resort, you can also Dispose the Client, it will cancel/abort all pending API calls

wiz0u commented 1 year ago

Addendum: To abort a file transfer in the middle, the correct way is to throw an exception from the progressCallback you can provide.