我了解任务(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
}