2

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

3 Answers 3

2

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I would make sure you synchronize access to said variable.
0

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 ....


}

2 Comments

I realized I just had my thread set up all wrong. Thanks for the help.
If I have a variable set up in my thread that determines whether or not we're done sending and then I use that in a while loop for the main part of the thread body - while (!sendingComplete){ do stuff }, then I'm assuming as soon as it exits the while loop the thread ends? Or is there something I need to do to specifically kill the thread? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.