使用后是否需要在 C# 中处理或终止线程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10698107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Do we need to dispose or terminate a thread in C# after usage?
提问by Aaron Azhari
I have the following code:
我有以下代码:
public static void Send(this MailMessage email)
{
if (!isInitialized)
Initialize(false);
//smtpClient.SendAsync(email, "");
email.IsBodyHtml = true;
Thread mailThread = new Thread(new ParameterizedThreadStart(
(o) =>
{
var m = o as MailMessage;
SmtpClient client= new SmtpClient("smtpserveraddress");
client.Send(m);
}));
mailThread.Start(email);
I want the mail sending to be done in the background without interfering with the main thread. I do not care when it is finished.
我希望邮件发送在后台完成而不干扰主线程。我不在乎它什么时候完成。
Do I need to somehow handle the dispose of the created thread (mailThread)? Or does it automatically dispose when it finishes its job?
我是否需要以某种方式处理创建的线程(mailThread)的处置?还是在完成工作后自动处理?
Please do not recommend the SendAsync method. I would like to create the thread manually. Mail.Send was only an example scenario.
请不要推荐 SendAsync 方法。我想手动创建线程。Mail.Send 只是一个示例场景。
Thank you.
谢谢你。
采纳答案by platon
NO!
不!
there is no need to dispose the Thread object (BTW, the Thread class does not provide the Dispose method).
不需要处理 Thread 对象(顺便说一句,Thread 类没有提供 Dispose 方法)。
回答by Marco
Thread is diposed when its routine comes at end.
So NO, you don't have to do it, it's not necessary (nor possible I think).
线程在其例程结束时被处置。
所以不,你不必这样做,它没有必要(我认为也不可能)。
回答by Jesse C. Slicer
Well, your SmtpClientshould be Dispose()'d. I'd use the Task Parallel Library instead of creating raw threads:
那么,你SmtpClient应该是Dispose()'d。我会使用任务并行库而不是创建原始线程:
public static void Send(this MailMessage email)
{
if (!isInitialized)
Initialize(false);
//smtpClient.SendAsync(email, "");
email.IsBodyHtml = true;
Task.Factory.StartNew(() =>
{
// Make sure your caller Dispose()'s the email it passes in at some point!
using (SmtpClient client = new SmtpClient("smtpserveraddress"))
{
client.Send(email);
}
});
}

![C# 路由:当前的操作请求 [...] 在以下操作方法之间是不明确的](/res/img/loading.gif)