是否可以调用 TidSMTP.Connect 一次,然后从线程中调用 TidSMTP.Send?
我正在编写一个使用 Indy 发送电子邮件的应用程序。
每条消息都由一个线程发送。
目前我正在线程内连接到 TidSMTP
,因此要发送 10 封邮件,我需要 10 个线程并且连接 10 次。
使用单个 TidSMTP
(在线程之外)是否安全(有哪些缺点?),调用一次 Connect
,然后调用 TidSMTP.Send 线程内?
TidSMTP
能正确管理吗?
注意:这个想法是避免每次都连接(如果可能的话),如果要发送很多电子邮件,这可能是一个优势。 (为此担心是否有意义,或者在每个线程中调用 Connect 就完全没问题?)。
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?).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不只使用 1 个 TIdSMTP 和一个 TList,其中存储 TIdMessage,并且在每次发送后从列表中释放 TIdMessage,在这种情况下,您可以避免开销并保持简单。
如果您想发送 200 封电子邮件,那么如果您启动 200 个线程,那么您的应用程序将仅使用这 200 个线程超过 200 Mb,更不用说在应用程序中启动这么多线程可能会出现问题。
底线添加一个 TList,在其中临时存储准备好的 TIdMessages,并在线程内添加一个 while 循环,该循环将检查列表中是否有任何要发送的消息,如果有则抓取、发送并从列表中删除。
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.
从技术上讲,您可以在一个线程中调用 Connect(),然后在其他线程中调用 Send()。但是,您必须序列化对 Send() 的访问,否则发送线程可能会相互重叠并破坏 SMTP 通信。 Dorin 建议将所有 SMTP 流量移至带有队列的单个线程,这是最佳选择。然而,队列本身需要以线程安全的方式访问,因此单独使用普通的 TList 或 TQueue 还不够。要么使用TThreadList(或Indy自己的TIdThreadSafeList)代替TList,要么用单独的TCriticalSection包装TQueue。
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.