运行一个Task,做点什么然后等待?

Run a Task, do something and then wait?

我熟悉 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
}

听起来您只想稍后在方法中等待:

public async void SomeMethod()
{
   var cameraTask = DoCameraWork();

   TextBox.Text = "Waiting For camera work";
   SendData();

   var result = await cameraTask;
   TextBox.Text = result ? "Camera work finished OK"
                         : "Eek, something is broken";
   ...
}