【发布时间】:2020-04-17 02:39:23
【问题描述】:
(.Net 3.1,Visual Studio 2019)
在DevExpress代码示例中:https://github.com/DevExpress-Examples/blazor-server-dxdatagrid-export/blob/19.2.2%2B/CS/DxDataGridExportingWithReports/Helpers/ExportMiddleware.cs,下面的http中间件代码得到了
的警告不通过TaskScheduler就不要创建任务...
重写代码以启动新任务的正确方法是什么?
public class ExportMiddleware : IMiddleware
{
......
public Task InvokeAsync(HttpContext context, RequestDelegate next)
{
......
_ = await new TaskFactory().StartNew(() => // warning: Do not create tasks without passing a TaskScheduler
{
report.CreateDocument();
using (MemoryStream fs = new MemoryStream())
{
if (format == pdf)
report.ExportToPdf(fs);
else if (format == xlsx)
report.ExportToXlsx(fs);
else if (format == docx)
report.ExportToDocx(fs);
context.Response.Clear();
context.Response.Headers.Append("Content-Type", "application/" + format);
context.Response.Headers.Append("Content-Transfer-Encoding", "binary");
context.Response.Headers.Append("Content-Disposition", "attachment; filename=ExportedDocument." + format);
context.Response.Body.WriteAsync(fs.ToArray(), 0, fs.ToArray().Length);
return context.Response.CompleteAsync();
}
});
【问题讨论】:
-
你为什么要使用任务来完成这项工作?您认为创建自己的任务工厂在这里给您带来什么?
标签: c# asp.net asp.net-core devexpress task-parallel-library