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

青春壹個敷衍的年華 提交于 2019-12-30 06:21:41

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/43069026/stream-readtimeout-threw-an-exception-of-type-system-invalidoperationexceptio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!