2016-02-04 59 views
0

我正在使用C#代碼將xml發送到api終點並捕獲響應 我這樣做的方式如下 我有文件夾A 100 xmls,文件夾B 100 xmls和文件夾C 100 xmlsC# - Task.WaitAll()不等待所有任務完成

我循環通過每個文件夾,並在每個循環迭代我創建一個任務。可以稱之爲文件夾任務

文件夾任務循環遍歷每個文件夾中的所有xml並捕獲響應。這是在sendrequestandcaptureresponse()方法中完成的

我面臨的問題是在所有xml被處理之前的循環結束。對於所有300個XMLS(位於文件夾A,B和C中)觸發sendrequestandcaptureresponse()方法,但我得到的響應僅爲150(大約)XMLS

Task.WaitAll(tasklist)在等待所有XML響應

請在下面找到

代碼的代碼通過文件夾來遍歷它發送請求並捕捉[R

foreach(Folder in Folders){ 

      Task t=Task.Factory.StartNew(
       async() => 
          {         
           Httpmode.RunRegressionInHTTPMode(folderPath);           
          } 
         }).Unwrap();      
       tasklist.Add(t); 

     }   
Task.WaitAll(tasklist.ToArray()); 

代碼esponse

public void RunRegressionInHTTPMode(folderPath){ 


     try 
     { 
      string directoryPath = CurrServiceSetting.GetDirectoryPath(); 
      var filePaths = CreateBlockingCollection(folderPath+"\\Input\\");     
      int taskCount = Int32.Parse(CurrServiceSetting.GetThreadCount()); 

      var tasklist = new List<Task>(); 
      for (int i = 0; i < taskCount; i++) 
      { 
       var t=Task.Factory.StartNew(
          async () => 
          { 
          string fileName; 
          while (!filePaths.IsCompleted) 
          { 
           if (!filePaths.TryTake(out fileName)) 
            {          
             continue; 
            } 

           try{ 
            SendRequestAndCaptureResponse(fileName,CurrServiceSetting,CurrSQASettings,testreportlocationpath);           
           } 
           catch(Exception r) 
           { 
            Console.WriteLine("#####SOME Exception in SendRequestAndCaptureResponse "+r.Message.ToString());           
           } 
          } 
         }).Unwrap(); 
       tasklist.Add(t); 
      }     
      Task.WaitAll(tasklist.ToArray());     
     } 
     catch(Exception e) 
     { 

     } 
    } 

任何人都可以請指點我在這裏失蹤。我將任務作爲異步任務,並在任務結束時添加了Unwrap方法,但仍無法等到所有任務完成。

任何幫助將是偉大的。

在此先感謝

下面的添加

public void SendRequestAndCaptureResponse(string fileName,ServiceSettings curServiceSettings,SQASettings CurrSQASettings,string testreportlocationpath){    
     XmlDocument inputxmldoc = new XmlDocument ();    

     Stream requestStream=null; 
     byte[] bytes; 
     DateTime requestsenttime=DateTime.Now; 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url); 
     string responseStr = ""; 

     bytes = Encoding.ASCII.GetBytes (str4); 
     try{ 
      request.ContentType = "text/xml; encoding='utf-8'"; 
      request.ContentLength = bytes.Length; 
      Credentials credentials = new Credentials();   
      request.Credentials = new NetworkCredential (CurrSQASettings.GetUserName(), CurrSQASettings.GetPassword()); 
      request.Method = "POST"; 
      request.Timeout = Int32.Parse(curServiceSettings.GetTimeOut()); 
      //OVERRIDING TIME 
      requestsenttime=DateTime.Now; 
      requestStream = request.GetRequestStream ();   
      requestStream.Write (bytes, 0, bytes.Length);   
      requestStream.Close (); 
     } 
     catch(Exception e){ 
      return; 
     } 



     HttpWebResponse response; 
     try 
     { 
     response = (HttpWebResponse)request.GetResponse (); 
     if (response.StatusCode == HttpStatusCode.OK) 
     {   


     allgood = true; 
     Stream responseStream = response.GetResponseStream (); 
     responseStr = new StreamReader (responseStream).ReadToEnd (); 
     XmlDocument xml = new XmlDocument (); 
     xml.LoadXml (responseStr);  
     xml.Save(resultantactualxmlpath);   
     response.Close(); 
     responseStream.Close();   

     } 

     } 
     catch(Exception e){ 
      return; 
     } 

} 
+0

非常感謝Glorin。在這種情況下,請告知它期望的返回值。 ANY指針將會有所幫助。 –

+1

不要等待'void'方法/委託:https://msdn.microsoft.com/en-us/magazine/jj991977.aspx –

+0

如果拋出,會發生什麼;而不是返回;在你添加的最新功能?在我看來,你正在隱藏潛在的錯誤。 –

回答

1

的SendRequestAndCaptureResponse代碼你不等待內部任務:

foreach(Folder in Folders){ 

      Task t=Task.Factory.StartNew(
       async() => 
          {         
           await Httpmode.RunRegressionInHTTPMode(folderPath); // <--- await here           
          } 
         }).Unwrap();      
       tasklist.Add(t); 

     }   
Task.WaitAll(tasklist.ToArray()); 

爲此,你的迭代不會等待內任務結束 - 在每次迭代中,您只需創建一個任務並繼續。

更優雅的方式來創建任務將是:

var tasks = Folders.Select(p=> Httpmode.RunRegressionInHTTPMode(p)).ToArray(); 
Task.WaitAll(tasks); 

(錯字不敏感)