问题描述
我有一个带有PictureBox的Windows窗体。我想在后台使用Timer和Task检查图像更新并刷新新图像是否可用。
我对使用Task感到困惑,是否需要使用await和async。
我不希望在运行Task时阻止UI。
在这里查看:http:/ /dotnetcodr.com/2014/01/01/5-ways-to-start-a-task-in-net-c/
他使用异步方法和等待,但我发现调用异步方法的唯一方法是使用await。但是那个调用它的方法应该使用await等来调用它。
但是我不能让所有的方法都异步吗?
我还想过使用Tasks和async我不应该等待吗?
过去我使用的是backgroundWorker并且没有等待?!
void timerRefreshImage_Elapsed( object sender,System.Timers.ElapsedEventArgs e )
{
任务t = 新任务(()= > RefreshImage ());
t.Start();
}
私有 void RefreshImage()
{
尝试
{
Task.Run(()=> GetCameraImage(真跨度>));
}
catch (例外t)
{
throw t;
}
}
更新图像的最佳方法是什么? ?
I have a Windows Form with a PictureBox. I want to use and Timer and Task in the background to check for Image updates and refresh if new Image is available.
I am getting confused using Task and whether I need to use await and async.
I don't want the UI to be blocked while running Task.
Looking here: http://dotnetcodr.com/2014/01/01/5-ways-to-start-a-task-in-net-c/
he uses async method and await but I found only way to call an async method is to use await. But then that method which is calling it should call it using await and so on.
But I can't make all methods async?
Also I thought by using Tasks and async I should not have to wait?
In the past I used backgroundWorker and did not wait?!
void timerRefreshImage_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { Task t = new Task(() => RefreshImage()); t.Start(); } private void RefreshImage() { try { Task.Run(()=>GetCameraImage(true)); } catch (Exception t) { throw t; } }
What would be the best approach(es) to update the images?
这篇关于C#Timer和Task-使用async和await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!