关于多线程:使用后,是否需要在C#中释放或终止线程?

Do we need to dispose or terminate a thread in C# after usage?

我有以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
        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);

我希望邮件发送在后台完成而不干扰主线程。 我不在乎什么时候完成。

我是否需要以某种方式处理创建的线程(mailThread)的处理?
还是在完成工作时自动处理?

请不要推荐SendAsync方法。 我想手动创建线程。 Mail.Send只是一个示例方案。

谢谢。


没有!

不需要处理Thread对象(顺便说一句,Thread类不提供Dispose方法)。


当线程的例程结束时,线程被丢弃。
所以不,您不必这样做,这是没有必要的(我也不可能)。


好吧,您的SmtpClient应该是Dispose()。 我会使用任务并行库而不是创建原始线程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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);
        }
    });
}