12

我创建了一种使用如下交换服务器读取收件箱新消息的方法。如何将这些 IEnumerable 集合添加到队列并异步处理队列中的每个项目列表?

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);
}
4

2 回答 2

2

如果您的 .NET 是 4.0 或 smth,您是否尝试过AsParallel扩展方法?

于 2012-12-19T08:35:11.000 回答
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。

于 2012-12-19T07:17:18.473 回答