geoff swartz
geoff swartz

Reputation: 31

threading & lambda in c#

I have the following code which sends out a batch of emails to our list of recipients every 60 seconds. What I'm not sure how to do is get to the completed part of the thread so that when it's done I can record the final status of how many emails were sent. Is this possible in a lambda style thread or do I have to do something else? thanks.

(new Thread(()=>
{
    message.To.Clear();

    var emailsToSend = memberlist.Skip(currentCount).Take(takeCount).ToList();

    foreach (var email in emailsToSend)
    {
        message.To.Add(new MailAddress(email.Email));
        //for logging purposes
        campaign.SentTo.Add(new BroadcastEmailCampaignSentTo
        {
            MemberId = email.MemberId,
                Email = email.Email,
                DateSent = DateTime.Now
        });
    }
})).Start(pauseTime);

Upvotes: 2

Views: 279

Answers (3)

spookycoder
spookycoder

Reputation: 1063

I would suggest to use Tasks, not threads, I throwed something together quickly to show the concept:

        string[] emailsToSend = { "[email protected]", "[email protected]", "[email protected]" };

        List<Task> tasks = new List<Task>();

        foreach (var email in emailsToSend)    {
            var e = email;
            tasks.Add(Task.Factory.StartNew(() => { Console.WriteLine("Sending Email to {0}", e); Thread.Sleep(5000); }));
        }

        Task.Factory.ContinueWhenAll(tasks.ToArray(), (_) => { Console.WriteLine("All Emails sent!"); });

        Console.ReadKey();

Upvotes: 2

linepogl
linepogl

Reputation: 9335

Just add this inside the body of the function, before the foreach:

if (emailsToSend.Count == 0) {
   // ok, finished sending,  
   // time to record the status here.
}
else {
   foreach ....


}

Upvotes: 0

jason
jason

Reputation: 241641

What I'm not sure how to do is get to the completed part of the thread so that when it's done I can record the final status of how many emails were sent.

Just capture a variable and mutate it in the lambda. Just be careful. If you capture it multiple times, the threads will share the same instance and could end up walking all over each other. You will have to synchronize access.

Upvotes: 1

Related Questions