C# 多线程编程 - 使用Thread类创建线程

使用Thread类可以创建和控制线程。使用Thread类需要引入系统的System.Threading命名空间。

下面简单示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadDemo
{
    class Program
    {
        static void ThreadMain()
        {
            Console.WriteLine("Running in the thread {0}, id: {1}",Thread.CurrentThread.Name, Thread.CurrentThread.ManagedThreadId);
        }

        static void Main(string[] args)
        {
            Thread t1 = new Thread(ThreadMain);
            t1.Name = "MyThread";
            t1.Start();
            Console.WriteLine("This is the Main thread");

            Console.ReadKey();            
        }
    }
}

这里不能保证哪个结果显输出,线程由操作系统调度,每次哪个线程在前面是不同的。

 

使用Thread类创建的线程默认的是前台线程,线程池中的线程总是后台线程。

  • 前台线程
  • 后台线程

前台线程在Main方法结束后,还会执行,一直到所有前台线程都完成任务了,程序才会结束。

后台线程在Main方法结束的时候,也会随之一起结束。

 

后台线程非常适合完成后台任务。例如关闭WORD应用程序,拼写检查继续运行其进程就没有意义。这样可以将这个进程设置为后台进程。

通过设置线程的IsBackground属性可以设置是否为后台进程。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ForegroundThread
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t1 = new Thread(ThreadMain);
            t1.Name = "MyNewThread1";
            t1.IsBackground = true;
            t1.Start();
            Console.WriteLine("Main Thread ending now...");
        }

        static void ThreadMain()
        {
            Console.WriteLine("Thread {0} started", Thread.CurrentThread.Name);
            Thread.Sleep(3000);
            Console.WriteLine("Thread {0} completed", Thread.CurrentThread.Name);
        }
    }
}

转载于:https://www.cnblogs.com/herbert/archive/2010/06/25/1765240.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值