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

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

I think maybe the reason is this error, but I could not 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));
}

      

+3


source to share


1 answer


The reason for this exception is probably because you are Dispose

stream

right after starting the task.

The statement using

calls Dispose

on the instance stream

when the execution of this block leaves this block. You can either remove this operator using

, or - if your method already exists async

- you can simply await

call SendPhotoAsync()

. There is no reason to use a different stream 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 call await

takes care that the finally

statement block using

(where it stream.Dispose()

will be called) is only executed after the Task

return is SendPhotoAsync

complete.

+4


source







All Articles