【发布时间】:2015-03-18 23:25:38
【问题描述】:
我熟悉 Tasks、asyn/await 等的基础知识,但我没有做太多的高级工作,而且我有点卡在一个问题上。我有一种与相机系统进行通信的方法。摄像头代码使用 Task 在自己的线程上运行。
public Task<bool> DoCameraWork()
{
bool Result = true;
return Task.Run<bool>(() =>
{
for (int i = 0; i < 10; i++)
{
// Do something which will set Result to True or False
if (Result)
break;
else
Task.Delay(1000);
}
return Result;
});
}
我想要做的是启动任务(DoCameraWork),更新 UI,调用另一个方法,然后等待任务完成后再继续。
实现这一目标的最佳方法是什么?这是一个模拟方法,我希望能解释更多。是的,代码很差,但它只是为了解释我想要实现的目标。
// Running on UI Thread
public async void SomeMethod()
{
DoCameraWork(); // If I do await DoCameraWork() then rest of code won't process untill this has completed
TextBox.Text = "Waiting For camera work";
SendData(); // Calls a method to send data to device on RS232, notthing special in this method
// Now I want to wait for the DoCameraWork Task to finish
// Once camera work done, check result, update UI and continue with other stuff
// if result is true
// TextBox.Text = "Camera work finished OK";
// else if result is false
// TextBox.Text = "Camera work finished OK";
// Camera work finished, now do some more stuff
}
【问题讨论】:
-
你在开发什么平台?
标签: c# async-await task