我以這種方式使用了 c# 中的任務:
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);
}
但我需要在 C 中做一些事情。
有一種方法可以在 c 中遷移此代碼嗎?
謝謝 !
uj5u.com熱心網友回復:
或多或少的直接翻譯可能會std::future
使用std::async
.
免責宣告:我沒有一點 C# 知識,剛剛閱讀了它的Task
一點。我想這就是你想要的。
- 在 C 中,我們使用
std::chrono::duration
s 而不是普通int
的 s。時鐘的解析度通常遠高于毫秒,所以我選擇了std::chrono::steady_clock
支持的任何持續時間。因此,您可以通過它std::chrono::milliseconds
或std::chrono::seconds
- 它會做正確的事情。
#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()};
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/508352.html