简体   繁体   中英

Is it possible to call TidSMTP.Connect once and then from threads call TidSMTP.Send?

I am writing an app that sends e-mail messages using Indy.

Every message is sent by a thread.

Currently I am connecting to TidSMTP inside the thread, so for sending 10 mails, I need 10 threads and I connect 10 times.

Is it safe (which are the drawbacks?) of having a single TidSMTP (outside of the thread), call Connect once and then call TidSMTP.Send inside the thread?

Will TidSMTP manage thing correctly?

Note: the idea is to avoid to connect every time (if possible), in case of many emails to be sent it could be an advantage. (does it makes sense to get worried for this, or calling Connect in every thread is pefectly ok?).

Why don't you use only 1 thead in which you have a TIdSMTP and a TList in which you store TIdMessage's and after each send you free the TIdMessage from the list, in this case you avoid overhead and keep it simple. What if you want to send 200 e-mails, well if you start 200 threads then your application will use over 200 Mb only for those 200 threads not to mention that there can be problems starting that many threads in your application. Bottom line add a TList in which you temporarily store prepared TIdMessages and inside the thread a while loop that will check if the list has any messages to send, if it has then grab, send and remove from list.

Technically, you can call Connect() in one thread and then call Send() in other threads. However, you would have to serialize access to Send(), otherwise the sending threads can overlap each other and corrupt the SMTP communication. Dorin's suggestion to move all of the SMTP traffic to a single thread with a queue is the best choice. However, the queue itself needs to be accessed in a thread-safe manner, so using a plain TList or TQueue by itself it not good enough. Either use TThreadList (or Indy's own TIdThreadSafeList) instead of TList, or wrap the TQueue with a separate TCriticalSection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM