【发布时间】:2021-07-03 10:01:53
【问题描述】:
我正在尝试使用 System.Drawing.Printing.PrintDocument OnPrintPage 方法打印文档页面。
我需要调用外部服务来获取打印当前页面所需的测量值。当我调用 API 时,图形对象似乎因为多线程(?)而被锁定,并且当我在从 API 获取数据后尝试使用它时抛出异常。在打印文档之前无法获取数据。有什么办法可以避免这种阻塞?
protected override async void OnPrintPage(PrintPageEventArgs e)
{
var location = await foo.CallWebAPI();
//Do something with Graphics
e.Graphics.DrawLine(....);
//ERROR - Argument Exception
}
编辑:
我忘记在签名中添加异步,但这不是我的问题的一部分。在等待调用后,调试器中的图形对象似乎被锁定/处置。它在任何图形字段上显示 ArgumentException。 设法通过使用结果而不是等待呼叫来解决它,但我想知道是否有更好的解决方案。
var location = foo.CallWebAPI().Result;
【问题讨论】:
-
事件处理程序应定义为
async,以便您能够在其中使用await关键字:protected override async void OnPrintPage(PrintPageEventArgs e) { ... }。但是您的示例代码中的foo与location有什么关系...?你得到了什么例外? -
请将异常的消息和堆栈跟踪作为文本添加到您的问题中。
-
but I wonder if there is any better solution- 它是not really a solution。
标签: c# .net asynchronous printing system.drawing