Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an IEumerable Collection to a Queue and Process each item asynchronously in .NET?

Tags:

c#

.net

I have created a method for reading inbox new messages by using exchange server like below.How to add these IEnumerable collection to a Queue and Process each List of item inside the queue asynchronously?

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

The below are the process i need to call asynchronously by using each items in the queue

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);
}
like image 610
Jameel Moideen Avatar asked Dec 19 '12 07:12

Jameel Moideen


1 Answers

If your .NET is 4.0 or smth, did you try AsParallel extension method?

like image 164
vyakhir Avatar answered Oct 22 '22 01:10

vyakhir