2

I have used the tasks in c# in this way:

static async Task<string> DoTaskAsync(string name, int timeout)
{
   var start = DateTime.Now;
   Console.WriteLine("Enter {0}, {1}", name, timeout);
   await Task.Delay(timeout);
   Console.WriteLine("Exit {0}, {1}", name, (DateTime.Now - start).TotalMilliseconds);
   return name;
}

public Task DoSomethingAsync()
{
    var t1 = DoTaskAsync("t2.1", 3000);
    var t2 = DoTaskAsync("t2.2", 2000);
    var t3 = DoTaskAsync("t2.3", 1000);

    return Task.WhenAll(t1, t2, t3);
}

but I need to do the some in c++.

There is a way to migrate this code in c++ ?

Thanks !

2
  • There are several options for a direct translation, but rarely is a direct translation the right solution. Instead assess the behaviour you want on a grander scale and see if C++ offers a different path to attaining it that will serve your goals better. Commented Sep 14, 2022 at 18:56
  • 1
    Do you want C++ or C++/CLI Commented Sep 14, 2022 at 20:52

1 Answer 1

4

A more or less direct translation would probably use C++ std::futures returned by std::async.

Disclaimer: I don't have bit of C# knowledge and just read about its Tasks a bit just now. I think this is what you are going for.

  • In C++ we use std::chrono::durations instead of plain ints. The resolution of the clocks is often much higher than milliseconds, so I selected to go for whatever duration the std::chrono::steady_clock supports. You can thereby pass it a std::chrono::milliseconds or std::chrono::seconds - and it will do the right thing.
#include <array>
#include <chrono>    // clocks and durations
#include <format>    // std::format
#include <future>    // std::async
#include <iostream>
#include <string>
#include <thread>    // std::this_thread::sleep_for

auto DoTaskAsync(std::string name, std::chrono::steady_clock::duration timeout)
{
    return std::async(std::launch::async,
        [name=std::move(name),timeout] {
            auto start = std::chrono::steady_clock::now();
            std::cout << std::format("Enter {0}, {1}\n", name, timeout);

            std::this_thread::sleep_for(timeout);
            
            std::cout << std::format("Exit {0}, {1}\n", name,
                std::chrono::duration_cast<std::chrono::milliseconds>(
                    std::chrono::steady_clock::now() - start));
            
            return name;
        });
}

std::array<std::string, 3> DoSomethingAsync() {
    using namespace std::chrono_literals;
    auto t1 = DoTaskAsync("t2.1", 3000000000ns); // nanoseconds
    auto t2 = DoTaskAsync("t2.2", 2000ms);       // milliseconds
    auto t3 = DoTaskAsync("t2.3", 1s);           // seconds
    return {t1.get(), t2.get(), t3.get()};
}

Demo

Sign up to request clarification or add additional context in comments.

6 Comments

Side note: You have to be compiling against the C++20 Standard to get all the goodies used here, so at this time you'll need a fairly up-to-date compiler and almost certainly have to select C++20 with a compiler option.
@user4581301 Absolutely. I wanted to stay as close to OPs code as possible so I threw things in that my normal compiler doesn't even support. At least MSVC supports it all. It's probably not long before the other vendors catch up. :-) C++20 should be default for any new project though so I don't see that as a big problem.
Still clawing my way up to C++17 as the minimum for new projects. Tooling for some of the stuff I work on is sparse.
@user4581301 Tell me about it. I have to fight gcc 4.7.3 on a daily basis. It doesn't even know thread_local, much less C++17.
Thank you this is what I need. However I have C++17. The content of DoTaskAsync is only and example can be only Print("Hello word"). There is a way to extend compatibility with C++17 ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.