'stream.ReadTimeout'引发了类型'System.InvalidOperationException'的异常,将照片发送给电报机器人 [英] 'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException' sending photo to telegram bot

查看:1301
本文介绍了'stream.ReadTimeout'引发了类型'System.InvalidOperationException'的异常,将照片发送给电报机器人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面编写了用于将照片发送到我的机器人的代码,但是在我的信息流中,我有两个读写例外,并且我的照片未发送.

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引发了类型为'System.InvalidOperationException'的异常

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.

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

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

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

由编译器为此await调用创建的状态机要注意,只有在由using语句返回的Task之后,才执行using语句的finally块(其中将调用stream.Dispose()). SendPhotoAsync已完成.

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.

这篇关于'stream.ReadTimeout'引发了类型'System.InvalidOperationException'的异常,将照片发送给电报机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆