最终编辑:问题与此异步实现无关。第一个答案帮助我移动了足够的东西,用一双新的眼睛看问题。谢谢,伙计们。
我正在使用我的应用中的IP摄像头,通过httpclient(请求和接收图像)和websocket(通过websocket-sharp,以接收数据)。
现在我只是打开websocket并要求一个图像(循环将在稍后出现)。询问图像是我做的最后一件事。
当我将图像请求定义为
时string picloc = "[redacted]";
Stream imgstream = await client.GetStreamAsync(picloc).ConfigureAwait(false);
Bitmap blah2 = new Bitmap(imgstream);
BMPReadyEventArgs args = new BMPReadyEventArgs();
args.BMP = blah2;
BitmapReady(this, args);
应用程序运行所有代码并冻结。如果我将ConfigureAwait项关闭,await会将控制权交还给UI代码,它将到达所述代码的末尾,冻结几秒钟然后加载图像。
在那里使用configureawait(false)它将加载图像然后冻结。我认为我从请求中获得的流立即开始,所以如果它不必等待上下文(?)它基本上同步运行。说实话,我还是不太了解configureawait实际上做了什么,或者人们谈论的上下文实际意味着什么,但这种行为让我觉得UI冻结与代码的异步性质无关。
我无法通过使用F11看到调试器跳到意想不到的位置(虽然这在与异步代码一起使用时似乎有一些缺点),它确实似乎只是到达代码的末尾并且冻结了几秒钟。
这引出了几个问题。
当达到代码结束时,UI是否会一直冻结,如果是,我是否需要制作某种UI刷新代码?
而且,或者更模糊,
我的异步实现是否存在可能导致此冻结的问题?
编辑:完整方法:
public async void DownloadJPG()
{
string picloc = "[redacted]";
Stream imgstream = await client.GetStreamAsync(picloc).ConfigureAwait(false);
Bitmap blah2 = new Bitmap(imgstream);
BMPReadyEventArgs args = new BMPReadyEventArgs();
args.BMP = blah2;
BitmapReady(this, args);
}
来自
private async void HoldingPattern()
{
textBox1.Text = wsmanager.passer;
connector.BitmapReady += (sender, e) =>
pictureBox1.Image = e.BMP;
connector.DownloadJPG();
}
edit2:事件处理程序:
public event EventHandler<BMPReadyEventArgs> BitmapReady;
BMPReadyEventArgs
class BMPReadyEventArgs:EventArgs
{
public Bitmap BMP {get;set;}
}
答案 0 :(得分:0)
你的方法是复杂化的方法
public async Task<Image> DownloadJPGAsync()
{
string picloc = "[redacted]";
Stream imgstream = await client.GetStreamAsync(picloc).ConfigureAwait(false);
Bitmap blah2 = new Bitmap(imgstream);
return blah2;
}
现在来自异步事件处理程序
public async void Button1_Click()
{
var image = await connector.DownloadJPGAsync();
pictureBox1.Image = image;
}