运行任务,做一些事情,然后等待?

时间:2015-03-18 15:23:14

标签: c# async-await task

我熟悉任务的基本知识,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
}

1 个答案:

答案 0 :(得分:5)

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

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";
   ...
}