簡體   English   中英

如何判斷我的代碼是否正在異步運行?

[英]How can I tell if my code is running async?

這是我第一次嘗試讓代碼異步運行,但我不知道它是否真的如此。 function 下載報告沒有“等待”並且有警告說它將同步運行。

我正在嘗試同時下載多個報告,然后將 zip 全部下載到一個文件中。

結果符合預期,但我想確定代碼實際上是異步執行的。

static async Task Main(string[] args)
{
    string folderName = "Batch123";
    string fullDir = Path.Combine(ConfigurationManager.AppSettings["path"], folderName);
    Directory.CreateDirectory(fullDir);

    await RunReports(folderName);

    string zipPath = Path.Combine(ConfigurationManager.AppSettings["path"], "Zip", folderName);
    Directory.CreateDirectory(zipPath);
    ZipFile.CreateFromDirectory(fullDir, Path.Combine(fullDir, zipPath, "CRAs.zip"));           
}

private static async Task RunReports(string folderName)
{

    string[] dunsToProcess = new string[] {"d1"
                                            ,"d2"
                                            ,"d3"
                                            };

    await Task.WhenAll(dunsToProcess.Select(i => DownloadReport(i, folderName)));
}
private static async Task DownloadReroport(string DUNS, string folderName)
{
    NetworkCredential cred = new NetworkCredential(ConfigurationManager.AppSettings["networkUser"]
                                                    , ConfigurationManager.AppSettings["networkPassword"]);
    string fullPath = Path.Combine(ConfigurationManager.AppSettings["path"], folderName, string.Format("CRA for DUNS {0}.pdf", DUNS));
    WebClient wc = new WebClient();
    wc.Credentials = cred;
    wc.DownloadFile(@"http://xxxxxxx&pcDUNS=" + DUNS
                    , fullPath);
}

我希望它是正確的,因為它將成為許多其他變化的基礎。 如果沒有,你能指出我做錯了什么。

隨意用我的代碼嘲笑任何東西。!! 我根本沒有接受過 c# 培訓。

謝謝你。

我相信您指的是線程和任務,並試圖找到異步的東西。

首先,我不確定你在做什么以及當你的主要方法是任務時它是如何工作的,這對我來說毫無意義,所以,請嘗試以下操作:

  1. 讓 main 成為默認值,在此聲明更改中沒有任何事情可做
  2. 制作 class 正在做你想做的事(可能下載)
  3. 然后使任務或線程及時調用許多任務或線程。 請記住,對其中許多沒有意義,您可能希望限制及時執行的任務/線程的數量。 您可能希望識別所有任務,或者您可能只想等待所有任務執行,您的需要和決定,但是 Task 具有屬性 IsCompleted、IsCanceled 等......如果您正在生成線程,您可能想要調查以下類和方法:

手動重置事件等待句柄

作為簡短的簡歷,如果我什至能夠理解您在此代碼中嘗試執行的操作,那么您的方法是錯誤的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM