[英]Telegram Bot Console.Readline Block Whole My Host when I Run my Telegram Receive as Background Service (IHostedService)
I have the project that have API Endpoints And Background TelegramBot Communication Background service as You Can See My BackGround Service at Below:我的项目具有 API 端点和后台 TelegramBot 通信后台服务,您可以在下面看到我的后台服务:
public class BackgroundWorker: BackgroundService
{
private readonly IOptions<TelegramSettings> _telegramSettings;
private readonly IOptions<SqliteConnectionString> _sqlite;
public BackgroundWorker(IOptions<TelegramSettings>
telegramSettings, IOptions<SqliteConnectionString> sqlite)
{
_telegramSettings = telegramSettings;
_sqlite = sqlite;
}
public override async Task StartAsync(CancellationToken
cancellationToken)
{
await base.StartAsync(cancellationToken);
}
protected override Task ExecuteAsync(CancellationToken
stoppingToken)
{
var telegramSocial = new
TelegramSocial(_telegramSettings,_sqlite);
telegramSocial.ReceiveMessage();
return Task.CompletedTask;
}
}
And my Telegram Bot That Receive Like Below:我的Telegram Bot接收如下:
public void ReceiveMessage()
{
using var cts = new CancellationTokenSource();
// StartReceiving does not block the caller
//thread.Receiving is done on the ThreadPool.
var receiverOptions = new ReceiverOptions
{
AllowedUpdates = { } // receive all update types
};
_botClient.StartReceiving(HandleUpdateAsync,
HandleErrorAsync, receiverOptions,
cancellationToken: cts.Token);
Console.ReadLine();
// Send cancellation request to stop bot
cts.Cancel();
}
enter code here
As You Can see Console.ReadLine() Blocks Whole My Host And My APIEndPoints Not Works如您所见,Console.ReadLine()阻止整个我的主机和我的APIEndPoints不起作用
Now What can i do to Fix This Problem or Somethings to replace with Console.ReadLine() .现在我能做些什么来解决这个问题或用Console.ReadLine()替换的东西。
Telegram.Bot 17.0.0 Telegram.Bot 17.0.0
Telegram.Bot.Extensions.Polling 1.0.0-alpha.1 Telegram.Bot.Extensions.Polling 1.0.0-alpha.1
.Net Core 5 .Net 核心 5
Sorry For Bad English.对不起英语不好。
Change The StartReceive Method And Use Just ReceiveAsync And Its Works And do not Block My Host Code Att Below:更改 StartReceive 方法并使用 ReceiveAsync 及其工作,不要阻止我的主机代码 Att 下面:
public async Task ReceiveMessage()
{
using var cts = new CancellationTokenSource();
// StartReceiving does not block the caller thread. Receiving is
//done on the ThreadPool.
var receiverOptions = new ReceiverOptions
{
AllowedUpdates = { } // receive all update types
};
await _botClient.ReceiveAsync(HandleUpdateAsync, HandleErrorAsync,
receiverOptions,
cancellationToken: cts.Token);
Console.ReadLine();
// Send cancellation request to stop bot
cts.Cancel();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.