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

Maryam Ghafarinia picture Maryam Ghafarinia · Mar 28, 2017 · Viewed 34.4k times · Source

I wrote below code for sending a photo to my bot, but in my stream, I have two exceptions for read and write and my photo was not send.

I think maybe the reason was this error, but I couldn't fix it:

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

Answer

René Vogt picture René Vogt · Mar 28, 2017

The reason for this exception is probably that you Dispose the stream immediatly after starting the task.

The using statement calls Dispose on the stream instance when execution leaves this block. You can either remove this using statement or - if your method already is async - you may simply await the call to SendPhotoAsync(). There is no reason to use another thread with 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);
}

The state-machine created by the compiler for this await call takes care that the finally block of the using statement (where stream.Dispose() will be called) is executed only after the Task returned by SendPhotoAsync has completed.