locked
How to use task inside For loop

    Question

  • Hi

    I need to use GetFileAsync and CopyAsync inside a for loop.

    The code structure is given, it only shows the code flow;

    for (...)

    {

    create_task GetFileAsync()

    {

    create_task CopyAsync()

    {

    Some other Save action();

    }

    }

    }

    How can I get a solution for this.

    Anyway thanx in adv.

    _Sujith

    Tuesday, August 21, 2012 11:12 AM

Answers

All replies

  • Hi Sujith,

    You can either use "create_iterative_task" in the concurrency::extras namespace or use the .get() / .then() as appropriate method from the task class. Reference - http://social.msdn.microsoft.com/Forums/en-US/winappswithnativecode/thread/2a753918-00bf-408f-9f0a-ff63650ed5a3

    -Sagar

    • Proposed as answer by Jesse Jiang Wednesday, August 22, 2012 6:31 AM
    • Marked as answer by Jesse Jiang Monday, August 27, 2012 6:15 AM
    Tuesday, August 21, 2012 5:47 PM
    Moderator
  • You need to put all the async actions within the continuations from the previous file function or you will find your code doesnt work as expected.

    I tried to save 8 files in my software and it got into a real mess until I put sequential saves in sequential continuations.

     


    n.Wright

    Tuesday, August 21, 2012 9:42 PM
  • Thanks to all

    Solved by using when_all feature

    _Sujith

    Friday, September 14, 2012 9:21 AM
  • you have to be careful to not overwhelm the system with tasks that perform IO. usually you want to serialize your work.  

    here is some code that I wrote that chains tasks together and runs them all serially.

        auto ct = cts.get_token();
        create_task(folder->CreateFileQuery()->GetFilesAsync()).then([this, ct](IVectorView<StorageFile^> ^files)
        {
            Output->Text += "Running task...\n";
            auto renameTasks = create_task([]{}, ct);
            for (auto file : files)
            {
                auto newName = StripUniqueQualfierFromFileName(file->Name->Data());
                if (newName)
                {
                    renameTasks = renameTasks.then([file, newName] { RenameIngoreCollisionAsync(file, newName); });
                }
            }

            renameTasks.then([this](task<void> result)
            {
                PickFolder->IsEnabled = true;
                Cancel->IsEnabled = false;
                try
                {
                    result.get();
                    Output->Text += "done\n";
                }
                catch (const task_canceled&)
                {
                    Output->Text += "task canceled\n";
                }
                catch (Exception ^ex)
                {
                    Output->Text += "done with failures:" + ex->Message + "\n";
                }
            }, task_continuation_context::use_current());
        }, ct);

    Saturday, September 15, 2012 5:38 AM
  • Thanx Chris
    Tuesday, September 18, 2012 9:52 AM