Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a Task, do something and then wait?

I am familiar with the basic of Tasks, asyn/await etc but I haven't done much advance stuff and I a little stuck on an issue. I have a method which does communication to a camera system. The camera code runs on its own thread using a 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;
         });
    }

What I want to be able to do is start the task (DoCameraWork), update UI, call another method and then wait for the task to finish before continuing.

Whats the best way to achive this? Here is a mock up method which I hope explains a bit more. Yes code is poor but its just to explain what I want to achieve.

// 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
}
like image 607
Gaz83 Avatar asked Mar 18 '15 15:03

Gaz83


1 Answers

Sounds like you just want to await later in the method:

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";
   ...
}
like image 67
Jon Skeet Avatar answered Sep 25 '22 19:09

Jon Skeet