Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Guarantee execution order between async methods

Discussion in 'Windows' started by K1kk0z90_Unity, Feb 12, 2015.

  1. K1kk0z90_Unity

    K1kk0z90_Unity

    Joined:
    Jun 2, 2013
    Posts:
    90
    Hi all! :)
    I wrote a little Unity plugin for Windows Store, that makes use of async methods to read and write text files. The problem is that, since IO methods are asynchronous, it happens, for example, that a file is attempted to be read before it has been opened. This is because the plugin user calls the methods to open the file and read it in this order, but async methods are not guaranteed to be executed in this order.
    How should I deal with this problem?
     
  2. Aurimas-Cernius

    Aurimas-Cernius

    Unity Technologies

    Joined:
    Jul 31, 2013
    Posts:
    3,627
    The proper way is to create a single async method and call other async method from it using await keyword.
    Alternative is to hook continuators to Task objects, returned by every async method.
     
    K1kk0z90_Unity likes this.
  3. K1kk0z90_Unity

    K1kk0z90_Unity

    Joined:
    Jun 2, 2013
    Posts:
    90
    Thank you very much for your answer.
    What do you mean when you say "hook continuators to Task objects"?
    Thank you again for your precious help! :)
     
  4. Aurimas-Cernius

    Aurimas-Cernius

    Unity Technologies

    Joined:
    Jul 31, 2013
    Posts:
    3,627
    Call first async method and get a Task Object for it (WinRT methods more often return IAsyncOperation, which has property AsTask to get a task for it).

    What you do next is call appropriate ContinueWith() on a task passing a in a delegate to call your next method. This method in turn returns you a new Task object to which you connect your third call and so on.

    You can find example in description of ContinueWith() method:
    https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx
     
    K1kk0z90_Unity likes this.
  5. K1kk0z90_Unity

    K1kk0z90_Unity

    Joined:
    Jun 2, 2013
    Posts:
    90
    I didn't know about the ContinueWith() method of Task, thank you very much! Now I'll look into it. Does it allow to keep the methods of my plugin separated? So that, for instance, the plugin user can call the method to open a file for reading and then call the method to read a line from that file?
     
  6. Aurimas-Cernius

    Aurimas-Cernius

    Unity Technologies

    Joined:
    Jul 31, 2013
    Posts:
    3,627
    Yes, just if those methods are all async, it's up to user to chain the tasks in the right order then.
     
    K1kk0z90_Unity likes this.