2016-06-24 53 views
1

我決定將生成PDF的方法轉換爲異步調用。異步調用不會產生所要求的PDF,我不知道爲什麼會這樣異步異步等待方法來生成pdf

誰調用異步操作如下客戶端:

public QuotationResponse CreateQuotation(IQuotation quotation) 
{ 
    ... 
    // Create Quotation PDF 
    _pdfWriter.GeneratePdfAsync(response); 
    return response; 
} 

負責生成PDF的類是以下:

public class Writer 
{ 
    //... other class methods 
    public async Task GeneratePdfAsync(QuotationResponse response) 
    { 
     await new Task(() => 
     { 
      var currentPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; 
      var formFile = Path.Combine(currentPath, Settings.Default.QUOTATION_TEMPLATE_PATH); 
      var newFile = Path.Combine(currentPath, Settings.Default.QUOTATION_PDF_PATH); 
      var reader = new PdfReader(formFile); 
      using (PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create))) 
      { 
       .... 
       // flatten form fields and close document 
       stamper.FormFlattening = true; 
       stamper.Close(); 
      } 
     }); 
    } 
} 

我懷疑我不是做正確的事情與異步 - 等待操作,但不知道是什麼。你能幫忙嗎?

+3

不會是異步的。你通過創建一個新任務沒有任何價值。說完這個,你的直接問題是你應該使用'Task.Run(..'而不是'new Task(...' –

+0

@ScottChamberlain)它不應該是無效的。整個pdf生成發生在GeneratePdfAsync方法中 – Nostradamus

+1

我起初沒有注意到GeneratePdfAsync是在第二個代碼示例中定義的,要添加Yacoub所說的內容,您應該永遠不需要執行'新任務(...'也是,您永遠不會等待從GeneratePdfAsync返回的任務 –

回答

2

你不應該使用Task構造函數。永遠。它絕對沒有有效的用例。完全一樣。對於任何類型的問題的任何一種方法。 Full details on my blog

由於沒有異步工作要做,你應該只使用同步方法:

public class Writer 
{ 
    //... other class methods 
    public void GeneratePdfAsync(QuotationResponse response) 
    { 
    var currentPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; 
    ... 
    } 
} 

如果你想從一個GUI應用程序調用此並不想阻止UI線程,那麼你可以通話它在後臺線程使用await Task.Run,因爲這樣的:

您的PDF生成代碼似乎
QuotationResponse response = await Task.Run(() => CreateQuotation(quotation));