c# - 异步代码不比同步版本快
问题描述
我对异步编程不是很有经验,所以请原谅我的无知。
我正在尝试异步生成 PDFS 列表以提高性能。
但是,无论是异步还是同步,代码的运行方式都是一样的:
Parallel Test MS: 10452
Async Test MS: 9971
Sync Test MS: 10501
有什么明显的我做错了,还是图书馆?我正在使用以下文档:https ://ironpdf.com/docs/questions/async/
主要的:
static async Task Main(string[] args)
{
var html = @"<h1>Hello World!</h1><br><p>This is IronPdfss.</p>";
Stopwatch stopwatch = new Stopwatch();
List<PdfDocument> pdfDocuments = new List<PdfDocument>();
List<string> htmlStrings = new List<string>();
for (int i = 0; i < iterations; i++)
htmlStrings.Add(html);
stopwatch.Start();
Parallel.ForEach(htmlStrings, htmlString =>
{
var document = RenderPdf(htmlString);
pdfDocuments.Add(document);
});
stopwatch.Stop();
Console.WriteLine($"Parallel Test MS: {stopwatch.ElapsedMilliseconds}");
stopwatch.Restart();
var tasks = htmlStrings.Select(async h =>
{
var response = await RenderPdfAsync(h);
pdfDocuments.Add(response);
});
await Task.WhenAll(tasks);
stopwatch.Stop();
Console.WriteLine($"Async Test MS: {stopwatch.ElapsedMilliseconds}");
stopwatch.Restart();
foreach (string h in htmlStrings)
{
var document = RenderPdf(h);
pdfDocuments.Add(document);
}
stopwatch.Stop();
Console.WriteLine($"Sync Test MS: {stopwatch.ElapsedMilliseconds}");
Console.ReadLine();
}
辅助方法:
private static async Task<IronPdf.PdfDocument> RenderPdfAsync(string Html, IronPdf.PdfPrintOptions PrintOptions = null)
{
return await Task.Run(() => RenderPdf(Html, PrintOptions));
}
private static IronPdf.PdfDocument RenderPdf(string Html, IronPdf.PdfPrintOptions PrintOptions = null)
{
var Renderer = new IronPdf.HtmlToPdf();
if (PrintOptions != null)
{
Renderer.PrintOptions = PrintOptions;
}
PdfDocument Pdf = Renderer.RenderHtmlAsPdf(Html);
return Pdf;
}
解决方案
private static async Task<IronPdf.PdfDocument> RenderPdfAsync(string Html, IronPdf.PdfPrintOptions PrintOptions = null)
{
return await Task.Run(() => RenderPdf(Html, PrintOptions));
}
这就是通常所说的“假异步”。这是一种具有异步签名的方法,它并不是真正的异步。它只是在线程池线程上运行的同步工作。因此,“异步”代码的行为与并行代码非常相似:它在线程池线程上运行每个渲染。
在这种情况下,操作受 CPU 限制,而不是 I/O 限制,因此同步或并行代码是正确的方法。例如,我认为并行 LINQ 是最好的方法。您不想在这里使用异步代码。
你的时间奇怪的是并行代码并不比同步代码快。对此的一种解释是 PDF 渲染已经是并行的,因此额外的并行性无济于事。另一种解释是某些东西将您的应用程序限制为只能在单个 CPU 内核上运行。
推荐阅读
- deep-learning - 为什么 CNN 中使用的图像大小通常是特定数字?
- dart - 如何通过手势传递到下面的对象?
- javascript - Vuejs SSR、Laravel 和 PHP V8Js 问题“窗口未定义”
- python - 重命名目录中的文件时的 If-Else
- javascript - 为什么fillText没有出现在画布中?
- javascript - 即使在使用 window.location 重定向后,Chrome 也会继续加载资源
- regex - 如何为我的词法分析器使用正则表达式转义字符串文字?
- c++11 - Visual Studio 2017 仅支持 c++11 功能?
- reactjs - Redux Saga 所有效果正确使用
- asp.net-core - 无法为实体类型指定过滤器表达式,因为它只能应用于层次结构中的根实体类型