2012-12-19 46 views
12

我已經創建了一個通過使用如下所示的交換服務器來讀取收件箱中新郵件的方法。如何將這些IEnumerable集合添加到隊列中並異步處理隊列中的每個列表項?如何將IEumerable集合添加到隊列並在.NET中異步處理每個項目?

private static IEnumerable<ExchangeEmailInformation> GetInboxItems(ExchangeService service) 
{ 
    var emailInformations = new List<ExchangeEmailInformation>(); 
    try 
    {  
     SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); 
     var itemview = new ItemView(int.MaxValue); 
     FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, itemview); 
     Console.WriteLine("\n-------------Result found:-------------"); 
     service.LoadPropertiesForItems(findResults, PropertySet.FirstClassProperties); 

     foreach (var item in findResults) 
     { 
      emailInformations.Add(new ExchangeEmailInformation 
      { 
       Attachment = item.Attachments ?? null, 
       Body = item.Body.BodyType == BodyType.HTML ? ConvertHtml.ToText(item.Body.Text) : item.Body.Text, 
       Subject = item.Subject, 
       RecievedDate = item.DateTimeReceived 
      }); 
     } 
    } 
    catch (Exception ee) 
    { 
     Console.WriteLine("\n-------------Error occured:-------------"); 
     Console.WriteLine(ee.Message.ToString()); 
     Console.WriteLine(ee.InnerException.ToString()); 
     Console.ReadKey(); 
    } 
    return emailInformations; 
} 

下面的是過程,我需要通過使用隊列

static void AddAttachment(string subject ,string docId, string user, string fileName) 
{ 
    var url = new StringBuilder(); 
    url.Append(string.Format("https://webdemo-t.test.com:8443/Services/Service/MyService.svc/AddAttachment?User={0}&Engagement={1}&FileName={2}&DocumentTrasferID={3}", user, subject, fileName, docId)); 

    Console.WriteLine(url.ToString()); 
    WebRequest request = WebRequest.Create(url.ToString()); 
    var credential = new NetworkCredential("user", "xxxx", "xxxx"); 
    request.Credentials = credential; 
    WebResponse ws = request.GetResponse(); 
    Encoding enc = System.Text.Encoding.GetEncoding(1252); 
    var responseStream = new StreamReader(ws.GetResponseStream()); 
    string response = responseStream.ReadToEnd(); 
    responseStream.Close(); 
    Console.WriteLine(response); 
} 

回答

1

每個項目可以開始爲每個附件的新任務異步調用。沒有必要考慮你產卵的任務數量。任務不會被映射到線程1. 1

foreach (var item in findResults) 
{ 
    emailInformations.Add(new ExchangeEmailInformation ...); 

    // start new task 
    Task.Factory.Start(() => { 
     AddAttachment(item.Subject, item.docId, item.User ...); 
    }) 
} 

此方法不要求您使用異步API。

另一種方法是利用WebRequest/WebResponse類的異步API。

+0

我想處理隊列中的每個項目asynchronosly – JEMI

+0

比你需要改善你的問題。你的算法的哪些步驟必須異步執行? – Lazin

+0

我已經通過添加我需要異步執行的方法更新了問題 – JEMI

2

如果你的.NET是4.0或者不適用,你試過AsParallel擴展方法嗎?

+1

+1 PLinq可以幫助您解決這個問題。 http://msdn.microsoft.com/en-us/library/dd997425.aspx –

+0

我需要處理隊列中的每個列表項 – JEMI

+0

爲什麼你不這樣做: foreach(var item in findResults。 AsParallel()){...} – vyakhir

相關問題