简体   繁体   中英

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:

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:

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

Now What can i do to Fix This Problem or Somethings to replace with Console.ReadLine() .

Telegram.Bot 17.0.0

Telegram.Bot.Extensions.Polling 1.0.0-alpha.1

.Net Core 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:

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM