I'm writing an own TelegramBot. In that Bot there is a function subscribe/unsubscribe. When user starts "Subscribtion" TelegramBot should send a message "1111" each three seconds. But after unsubscription message keep sending. Could someone help me with that issue?
Method for start subscription:
private async Task OnStartSubscribeAsync(string userName, long userId,
ITelegramBotClient _client, long chatId)
{
var user = new UserDTO
{
UserId = userId.ToString(),
UserName = userName
};
await _userService.StartSubscribeAsync(user);
await _client.SendTextMessageAsync(chatId, "You subscribed successfully ");
try
{
await CheckTick(_client, chatId);
}
catch (OperationCanceledException e)
{
await _client.SendTextMessageAsync(chatId, "STOPPED");
}
finally
{
tokenSource.Dispose();
}
var articles = await ReturnNewArticles();
foreach (var item in articles)
{
var linkButton = KeyboardGoOver("Перейти", (EncodeUrl(item.Href)));
await _client.SendPhotoAsync(chatId: chatId, photo: item.Image,
caption: $"*{item.Title}*",
parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown,
replyMarkup: linkButton);
}
}
Method for sending message with delay:
private Task CheckTick(ITelegramBotClient _client, long chatId)
{
return Task.Run(async () =>
{
tokenSource.Token.ThrowIfCancellationRequested();
while (true)
{
await Task.Delay(3000);
await _client.SendTextMessageAsync(chatId, "1111");
if (tokenSource.Token.IsCancellationRequested)
{
tokenSource.Token.ThrowIfCancellationRequested();
}
}
}, tokenSource.Token);
}
Method for unsubscribe:
private async Task OnStopSubscibeAsync(string userName, long userId,
ITelegramBotClient _client, long chatId)
{
var user = new UserDTO()
{
UserId = userId.ToString(),
UserName = userName
};
await _userService.StopSubscribeAsync(user);
tokenSource.Cancel();
await _client.SendTextMessageAsync(chatId, "You unsubscribed successfully");
}
Definition of tokenSource:
private CancellationTokenSource tokenSource = new();
I think there are some issues with CancelationToken
with threads. When I tried to debug, I didn't hit to block "catch".