'stream.ReadTimeout' 抛出 'System.InvalidOperationException' 类型的异常,将照片发送到电报机器人

'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException' sending photo to telegram bot

我写了下面的代码来向我的机器人发送照片,但是在我的信息流中,我有两个读写异常,我的照片没有发送。

我想可能是这个错误的原因,但我无法修复它:

stream.ReadTimeout threw an exception of type 'System.InvalidOperationException'

using (var stream = System.IO.File.Open("a.jpg", FileMode.Open))
{
    var fileToSend = new FileToSend("a.jpg", stream);
    Task.Run(() => bot.SendPhotoAsync(u.Message.Chat.Id, fileToSend).ConfigureAwait(false));
}

出现此异常的原因可能是您 Dispose 在开始任务后立即 stream

当执行离开此块时,using 语句在 stream 实例上调用 Dispose。您可以删除此 using 语句,或者 - 如果您的方法已经是 async - 您可以简单地 await 调用 SendPhotoAsync()。没有理由使用 Task.Run():

的另一个线程
using (var stream = System.IO.File.Open("a.jpg", FileMode.Open))
{
    var fileToSend = new FileToSend("a.jpg", stream);
    await bot.SendPhotoAsync(u.Message.Chat.Id, fileToSend).ConfigureAwait(false);
}

编译器为此 await 调用创建的状态机负责 using 语句的 finally 块(其中将调用 stream.Dispose())仅在 SendPhotoAsync 返回的 Task 完成后执行。