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

故事扮演 提交于 2019-11-30 19:19:47
René Vogt

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.

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