public class EMailer >> { >> public List<string> ManifestImportList { get; set; } >> >> public int PostAWBs() >> { >> object numRemainingLock = new object(); >> int numRemaining = ManifestImportList.Count; >> using (ManualResetEvent waitHandle = new ManualResetEvent(numRemaining == 0)) >> { >> foreach (string ManifestImport in ManifestImportList) >> { >> SmtpClient client = new SmtpClient(); >> MailMessage msg = new MailMessage(); >> >> // Build the message >> if (true) >> { >> try >> { >> string userState = string.Empty; >> client.SendCompleted += delegate >> { >> client.Dispose(); >> lock (numRemainingLock) >> { >> if (--numRemaining == 0) >> { >> waitHandle.Set(); >> } >> } >> }; >> client.SendAsync(msg, userState); // Send our email. >> } >> catch (Exception) >> { >> msg.Dispose(); >> } >> } >> } >> waitHandle.WaitOne(); >> } >> return 6; //Use whatever meaningful value >> } >> }(I've just made ManifestImport a string for simplicity) then you can call it like this:
internal class Program >> { >> public delegate int AsyncMethodCaller(); >> >> private static void Main(string[] args) >> { >> EMailer p = new EMailer(); >> p.ManifestImportList = new List<string> { "One", "Two" }; >> >> AsyncMethodCaller caller = new AsyncMethodCaller(p.PostAWBs); >> IAsyncResult result = caller.BeginInvoke(new AsyncCallback(CallbackMethod), "Test"); >> Console.ReadLine(); >> } >> >> public static void CallbackMethod(IAsyncResult ar) >> { >> AsyncResult result = (AsyncResult)ar; >> AsyncMethodCaller caller = (AsyncMethodCaller)result.AsyncDelegate; >> int i = caller.EndInvoke(ar); >> } >> }Disclaimer: haven't tested because I didn't have time to actually configure the SmtpClient :-{